home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 July: Mac OS SDK / Dev.CD Jul 96 SDK / Dev.CD Jul 96 SDK2.toast / Development Kits (Disc 2) / QuickDraw GX / Programming Stuff / Sample Code / Printing Samples / Printer Drivers… / ImageWriter--DTP renamer / NewApp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-10  |  80.3 KB  |  2,856 lines  |  [TEXT/MPS ]

  1. /*
  2.     copyright © 1991-1994 Apple Computer Inc.  All rights reserved.
  3.     
  4.     NewApp.c
  5.     This file contains all new API implementations for the ImageWriter driver.
  6.     
  7.     Modification history
  8.     03/19/91        TED                New file today
  9.     04/23/91        Sam Weiss        Changed Inherit to Forward
  10.     05/29/91        TED                Added manual feed and faster mode support
  11.     12/20/93        dmh                Sync'd with the shipping 1.0b3 GX driver.
  12.     03/24/94        Ken Hittleman    Updated manual feed to use gxTrayFeedInfo
  13.     03/30/94        Ken Hittleman    Added call to paper matching CheckStatus when switching to auto-feed
  14.      6/23/94        dmh                Added desktop printer renaming code.
  15.     07/05/94        Ken Hittleman    Removed set color and page size from IW I path, which blew cookies on it
  16.     08/26/94        dmh                Sync'd with the shipping 1.0.1 GX driver.
  17. */
  18.  
  19. #include <memory.h>
  20. #include <Devices.h>
  21. #include <Folders.h>
  22. #include <Errors.h>
  23. #include <ToolUtils.h>
  24. #include <Resources.h>
  25. #include <Packages.h>
  26. #include <PrintingDrivers.h>
  27. #include <PrintingMessages.h>
  28. #include <PrintingManager.h>
  29. #include <FixMath.h>
  30. #include <math routines.h>
  31. #include <math types.h>
  32. #include <Graphics Routines.h>
  33. #include <graphics libraries.h>
  34. #include <font library.h>
  35. #include <layout routines.h>
  36. #include <GXExceptions.h>
  37. #include <PrintingLibraries.h>
  38.  
  39. #include "CommonDefines.h"
  40.  
  41. OSErr MyRenameDTPs(void);
  42.  
  43. /* ------------------------------------------------------------------------------------    */
  44. /*    INTERNAL DEFINES                                                                    */
  45. /* ------------------------------------------------------------------------------------    */    
  46.  
  47. // positive error for aborting job and placing on hold
  48. #define kPutJobOnHoldErr            3
  49.  
  50. // timeout (in ticks) for the initial query
  51. #define kQueryTimeout                (7*60);
  52.  
  53. // things this specific driver puts into the DTP config file
  54. #define    kImageWriterConfigType        'ifig'
  55. #define kImageWriterConfigID        (0)            
  56. typedef struct
  57.     {
  58.         Boolean    hasColorRibbon;
  59.         Boolean    hasSheetFeeder;
  60.         Boolean    isImageWriterII;        // is this an ImageWriter II, or an older model?
  61.     } ImageWriterConfigRecord, *ImageWriterConfigPtr, ** ImageWriterConfigHandle;
  62.     
  63. /* Define special characters needed */
  64. #define ESCAPE                (char) 27
  65.  
  66. /* A record to hold a set margins command */
  67. typedef struct SetMarginsRecord
  68.     {
  69.     char        cEscape;                    // ESCAPE character
  70.     char        cCommand;                    // Set Margins command character
  71.     char        cIndentDistance[4];            // number of dots to indent
  72.     } SetMarginsRecord, *SetMarginsPtr;
  73. #define kSetMarginsCommand    (char)'F'        // ImageWriter II uses 'F' for tabbing
  74. #define kSetMarginsSize        6
  75.  
  76. /*     Define a record that can hold one scan line's worth of data, 1280 will
  77.     only happen at 160 dpi. and 14 inch wide paper.   */
  78. typedef struct ScanLineRecord
  79.     {
  80.     char            cColorEscape;                    // ESCAPE character
  81.     char            cSetColorCommand;                // Set color command
  82.     char            cColor;                            // The color
  83.     char            cEscape;                        // ESCAPE character
  84.     char            cCommand;                        // 'enter graphics' command
  85.     char            cLineLength[4];                    // number of dots to print
  86.     char            iTheData[2240];                    // Bits for the data, enough for one line's worth
  87.     } ScanLineRecord, *ScanLinePtr;
  88. #define kGraphicsCommand    (char)'G'        /* graphics printing command */
  89. #define kRepeatGroup        (char)'V'        /* repeat group character */
  90. #define kSetColorCommand     (char)'K'        /* Set color command */
  91. #define kGroupSize            6                /* Size of one group header */
  92.  
  93. #define kScanLineSize         3                /* NOTE: this is just the header size! */
  94.  
  95. #define kStatusCommand        "\033?"            /* request device status/config */
  96.  
  97. // Status flags for PAP status queries
  98. #define    kColorRibbonBit        0
  99. #define kSheetFeederBit        1
  100. #define kPaperOutBit        2
  101. #define kCoverOpenBit        3
  102. #define kOffLineBit            4
  103. #define kPaperJamBit        5
  104. #define kPrinterFaultBit    6
  105. #define kHeadMovingBit        7
  106. #define kPrinterBusyBit        8
  107.  
  108. #define kOutOfPaperMask            (  (0x8000 >> kPaperJamBit) | (0x8000 >> kCoverOpenBit) | (0x8000 >> kOffLineBit) )
  109. #define kPrinterOfflineMask        (  (0x8000 >> kOffLineBit) )
  110. #define kPrinterBusyMask        (  (0x8000 >> kPrinterBusyBit) )
  111. #define kHeadMovingMask            (  (0x8000 >> kHeadMovingBit) )
  112.  
  113. //<FF>
  114. /* ------------------------------------------------------------------------------------    */
  115. /*    INTERNAL ROUTINES                                                                */
  116. /* ------------------------------------------------------------------------------------    */
  117. void Long2Dec(long aLong, Ptr emitHere)
  118. /*
  119.     Converts a long into an ASCII string, padded with leading zeros.
  120. */
  121. {    
  122.     char    aString[10];
  123.     short    i, actualWidth, strLength;
  124.     
  125.     NumToString(aLong, aString);
  126.     
  127.     // Get the width of the string, check for being too small
  128.     strLength = aString[0];
  129.     actualWidth = strLength;
  130.     if (actualWidth < 4)
  131.         actualWidth = 4;
  132.         
  133.     // output the string, padding with the requested character
  134.     strLength = actualWidth-strLength;
  135.     for (i = 0; i < actualWidth; ++i)
  136.         {
  137.         *emitHere++ = (i < strLength) 
  138.             ? '0' : aString[(i+1)-(strLength)];
  139.         }
  140.         
  141. } // Long2Dec
  142.  
  143.  
  144. //<FF>
  145. /* ------------------------------------------------------------------------------------    */
  146. Boolean PrinterHasColorRibbon(gxPrinter thePrinter)
  147. /*
  148.     Returns true if the config file says that the printer is blessed with a color ribbon,
  149.     false if it is a black and white ribbon.
  150. */
  151. {
  152.     Boolean                        hasColor = true;
  153.     Str32                        deviceName;
  154.     OSErr                        anErr;
  155.     ImageWriterConfigHandle        configHandle;
  156.     
  157.     // if not formatting to a particular device, assume color ribbon, for widest range of colorSpaces
  158.     GXGetPrinterName(thePrinter, deviceName);
  159.     if (deviceName[0] != 0)
  160.         {
  161.         // if we are going to a particular device, assume no color, as that is more common
  162.         hasColor = false;
  163.         
  164.         anErr = GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, &(Handle)configHandle);
  165.         if (anErr == noErr)
  166.             {
  167.             hasColor = (**configHandle).hasColorRibbon;
  168.             DisposHandle((Handle) configHandle);
  169.             }
  170.         }
  171.     
  172.     return(hasColor);
  173.     
  174. } // PrinterHasColorRibbon
  175.  
  176.  
  177. //<FF>
  178. /* ------------------------------------------------------------------------------------    */
  179. gxViewDevice    NewDeviceResolutionViewDevice(void)
  180. /*
  181.     This routine creates a viewDevice and gives it a scale factor in it's mapping
  182.     appropriate for this device (144 dpi in the case of the IW)
  183. */
  184. {
  185.     gxViewDevice        vd;
  186.     
  187.     // create the viewDevices with a fake bitmap
  188.     {
  189.     gxShape        tempBitmap;
  190.     gxBitmap        aBitmap;
  191.     
  192.     aBitmap.pixelSize     = 1;
  193.     aBitmap.rowBytes     = 0;
  194.     aBitmap.width         = 0;
  195.     aBitmap.height         = 0;
  196.     aBitmap.image         = (char*)gxMissingImagePointer;
  197.     aBitmap.space         = gxNoSpace;
  198.     aBitmap.set         = nil;
  199.     aBitmap.profile     = nil;
  200.     
  201.     tempBitmap = GXNewBitmap(&aBitmap, nil);
  202.     vd = GXNewViewDevice(gxScreenViewDevices, tempBitmap);
  203.     GXDisposeShape(tempBitmap);
  204.     }
  205.  
  206.     // setup a mapping for a 144 (2X) viewDevice
  207.     {
  208.     gxMapping    vdMapping;
  209.     
  210.     ResetMapping(&vdMapping);
  211.     ScaleMapping(&vdMapping, ff(2), ff(2), ff(0), ff(0));
  212.     
  213.     GXSetViewDeviceMapping(vd, &vdMapping);
  214.     }
  215.     
  216.     return(vd);
  217.     
  218. } // NewDeviceResolutionViewDevice
  219.  
  220. //<FF>
  221. /* ------------------------------------------------------------------------------------    */
  222. Boolean    JobIsBest(long *imagewriterOptions)
  223. /*
  224.     Returns true if the current job is a final quality mode job, else returns false.
  225.     Also, returns the imagewriter rendering options.
  226. */
  227. {
  228.     Boolean            isFinal;
  229.     gxQualityInfo    jobQualitySettings;
  230.     long            itemSize = sizeof(jobQualitySettings);
  231.     OSErr            status;
  232.     Collection        jobCollection;
  233.     
  234.     // cache the collection
  235.     jobCollection = GXGetJobCollection(GXGetJob());
  236.     
  237.     // find out the info
  238.         
  239.     isFinal = false;
  240.     
  241.     status = GetCollectionItem(jobCollection, 
  242.                                     gxQualityTag, gxPrintingTagID, 
  243.                                     &itemSize, &jobQualitySettings);
  244.     
  245.     if ( (status == noErr) && (jobQualitySettings.currentQuality == (jobQualitySettings.qualityCount-1)) )
  246.         isFinal = true;
  247.     
  248.     ncheck( status );
  249.  
  250.     // we default to super res
  251.     *imagewriterOptions = kSuperRes;
  252.     itemSize = sizeof(imagewriterOptions);
  253.     status = GetCollectionItem(jobCollection, 
  254.                                     DriverCreator, 0, 
  255.                                     &itemSize, imagewriterOptions);
  256.                 
  257.     // and return the job quality mode
  258.     return(isFinal);
  259.     
  260. } // JobIsBest
  261.  
  262.  
  263. //<FF>
  264. /* ------------------------------------------------------------------------------------    */
  265.  
  266. OSErr    DoTheQuery(unsigned short * statusReturn, Boolean papStatus)
  267. /*
  268.     Returns in statusString the current status for the printer.  Returns various
  269.     errors from IO package if the printer's status could not be found.
  270. */
  271. {
  272.     OSErr                anErr = noErr;
  273.     long                statusLength;                    // status string size
  274.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  275.  
  276.     // default to a clear status
  277.     *statusReturn = 0;
  278.  
  279.     // send the query
  280.     if (papStatus)
  281.         {
  282.         char    statusString[255];                // returned string
  283.         
  284.         // According to the old IW driver, sometimes it will return all of the bits
  285.         // set.  This is an error, but we can just try again.
  286.         do {
  287.             statusLength = 255;
  288.             anErr = Send_GXGetDeviceStatus(nil, 0, statusString, &statusLength, nil);
  289.             } while ( (anErr == noErr) && (statusString[0] == 0xFF) );
  290.         
  291.         // return the printer status bits in the PAP case
  292.         *statusReturn = *(unsigned short*)&statusString[0];
  293.         }
  294.     else
  295.         {
  296.         char    statusString[8];                // returned string
  297.  
  298.         if ((**hGlobals).isImageWriterII)
  299.             {
  300.             statusLength = 8; // max number of characters to get back
  301.             anErr = Send_GXGetDeviceStatus(kStatusCommand, 2, statusString, &statusLength, "\p\n");
  302.                 
  303.             if ( anErr == gxAioTimeout)
  304.                 {
  305.                 *statusReturn = kPrinterOfflineMask;
  306.                 anErr = noErr;
  307.                 }
  308.             else
  309.                 {
  310.                 if (anErr == noErr)
  311.                     {
  312.                     // generate printer status bits in the serial case
  313.                     if (statusString[4] == 'C')
  314.                         *statusReturn |= 0x8000 >> kColorRibbonBit;
  315.                     if ( (statusString[5] == 'F') || (statusString[4] == 'F') )
  316.                         *statusReturn |= 0x8000 >> kSheetFeederBit;
  317.                     }
  318.                 }
  319.             }
  320.         }
  321.         
  322.     nrequire(anErr, Send_GXGetDeviceStatus);
  323.  
  324. // FALL THROUGH EXCEPTION HANDLING    
  325. Send_GXGetDeviceStatus:
  326.     
  327.     return(anErr);
  328.  
  329. } // DoTheQuery
  330.  
  331. //<FF>
  332. /* ------------------------------------------------------------------------------------    */
  333. OSErr FetchStatusString(unsigned short * statusReturn, Boolean papStatus, Boolean doRetry)
  334. /*
  335.     Returns in statusString the current status for the printer.  Returns various
  336.     errors from IO package if the printer's status could not be found.
  337.     
  338.     Handles reporting error conditions to the user.
  339. */
  340. {
  341.     OSErr            anErr;
  342.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  343.     
  344.     anErr = DoTheQuery(statusReturn, papStatus);        
  345.     nrequire(anErr, Send_GXGetDeviceStatus);
  346.     
  347.     // printer offline?
  348.     if (     
  349.         (doRetry) &&
  350.         ( ((*statusReturn) & kPrinterOfflineMask) != 0 )  
  351.         )
  352.         {
  353.         gxStatusRecord        theStat;
  354.         gxStatusRecord        *pStat = &theStat;
  355.         Boolean                printerIsFixed = false;
  356.         
  357.         pStat->statusOwner    = 'drvr';
  358.         pStat->statResId     = kDriverStatus;        
  359.         pStat->statResIndex = kCheckOnline;            
  360.         pStat->bufferLen      = 0;
  361.         pStat->dialogResult = nil;
  362.         
  363.  
  364.         // keep sending the user the alert until either
  365.         //  a) the problem resolves itself
  366.         //  b) the user responds via the dialog
  367.         //  c) some other (fatal) error happens
  368.         do
  369.             {
  370.             
  371.             // tell the user
  372.             anErr = GXAlertTheUser(pStat);
  373.             
  374.             // based on the user's response, continue or cancel
  375.             switch (pStat->dialogResult)
  376.                 {
  377.                 case ok:
  378.                     // retry
  379.                     break;
  380.                     
  381.                 case cancel:
  382.                     anErr = gxPrUserAbortErr;
  383.                     break;
  384.                     
  385.                 case 3:
  386.                     anErr = kPutJobOnHoldErr;
  387.                     break;
  388.                 }
  389.                 
  390.             // error to return from next idle
  391.             (**hGlobals).idleError = anErr;
  392.  
  393.             // if printer got suddenly turned online, do an OK
  394.             if ( (anErr == noErr) && ((papStatus) || (pStat->dialogResult == ok)) )
  395.                 {
  396.                 pStat->dialogResult = nil;
  397.                 (void) DoTheQuery(statusReturn, papStatus);        
  398.                 if (     
  399.                     ( ((*statusReturn) & kPrinterOfflineMask) == 0 ) 
  400.                     )
  401.                     {
  402.                     printerIsFixed = true;
  403.                     pStat->dialogResult = ok;
  404.                     anErr = noErr;
  405.                     }
  406.                 }
  407.                 
  408.             } while ((anErr == noErr) && (pStat->dialogResult == nil));
  409.  
  410.         // printer is okay -- no error
  411.         if (printerIsFixed)
  412.             anErr = noErr;
  413.         
  414.         // display "sending data to the printer" message
  415.         if (anErr == noErr)
  416.             anErr = GXReportStatus(kDriverStatus, kSendingData);
  417.         }
  418.  
  419. // FALL THROUGH EXCEPTION HANDLING    
  420. Send_GXGetDeviceStatus:
  421.     
  422.     return(anErr);
  423.     
  424. } // FetchStatusString
  425.  
  426. //<FF>
  427. /* ------------------------------------------------------------------------------------    */
  428. OSErr UpdateConfiguration(void)
  429. /*
  430.     This routine queries the printer for its hardware configuration (color ribbon and
  431.     sheet feeder options), and stores that info into the configuration file.
  432. */
  433. {
  434.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  435.     Str32                        deviceName;
  436.     OSErr                        anErr = noErr;
  437.     ImageWriterConfigHandle        configHandle;
  438.     ImageWriterConfigPtr        configPtr;
  439.     Boolean                        isImageWriterII = false;
  440.     ResType                        commType;
  441.     
  442.         
  443.     // find out what we are printing to, and how we are connected
  444.     GXGetPrinterName(GXGetJobOutputPrinter(GXGetJob()), deviceName);
  445.     anErr = GXFetchDTPData(deviceName, gxDeviceCommunicationsType, gxDeviceCommunicationsID, (Handle*)&configHandle);
  446.     nrequire(anErr, FetchCommType);
  447.     commType = **(ResType**)configHandle;
  448.     DisposHandle((Handle) configHandle);
  449.     
  450.     
  451.     // store away the communications type for future use
  452.     {
  453.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  454.     
  455.     (**hGlobals).commType = commType;
  456.     }
  457.     
  458.     // find out the original configuration
  459.     if (GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle*)&configHandle) == noErr)
  460.         {
  461.         // remember if we thought we had an IW2 when we started
  462.         configPtr = *configHandle;
  463.         (**hGlobals).isImageWriterII = isImageWriterII = configPtr->isImageWriterII;
  464.         DisposeHandle((Handle) configHandle);
  465.  
  466.         // if we aren't an ImageWriter II, bail out now - because the timeout takes two minutes!
  467.         if (!isImageWriterII)
  468.             return(noErr);            
  469.         }
  470.     else
  471.         {        
  472.         // if we don't know yet, assume IW2 for PAP else Serial
  473.         if (commType == 'PPTL')
  474.             isImageWriterII = true;
  475.             
  476.         // Assume IW 2 so we do the query for real
  477.         (**hGlobals).isImageWriterII = true;
  478.         }
  479.         
  480.     // make a handle to hold our configuration information for the printer
  481.     configHandle = (ImageWriterConfigHandle) NewHandle(sizeof(ImageWriterConfigRecord) );
  482.     anErr = MemError();
  483.     nrequire(anErr, NewHandle);
  484.     
  485.     // setup the default for the device - in case the query fails
  486.     configPtr = *configHandle;
  487.     configPtr->hasColorRibbon = false;
  488.     configPtr->hasSheetFeeder = false;
  489.     configPtr->isImageWriterII = true;
  490.     
  491.     // send initial data first to make sure IO handshaking is working,
  492.     // to load the first sheet of paper into the feeder (if any),
  493.     // and to take up "gear lash" in the device.  This is copied from
  494.     // what the old driver did.  Not doing this will cause the sheet
  495.     // feeder not to feed the initial page of data.
  496.     {
  497.     char    sendBuffer[11];
  498.     
  499.     // <CR>
  500.     sendBuffer[0] = 0x0D;
  501.     
  502.     // linefeed size = 18/144th
  503.     sendBuffer[1] = ESCAPE;
  504.     sendBuffer[2] = 'T';
  505.     sendBuffer[3] = '1';
  506.     sendBuffer[4] = '8';
  507.     
  508.     // reverse line feed
  509.     sendBuffer[5] = ESCAPE;
  510.     sendBuffer[6] = 'r';
  511.     sendBuffer[7] = 0x0A;
  512.     
  513.     // forward line feed
  514.     sendBuffer[8] = ESCAPE;
  515.     sendBuffer[9] = 'f';
  516.     sendBuffer[10] = 0x0A;
  517.     
  518.     anErr = Send_GXWriteData(sendBuffer, 11);
  519.     nrequire(anErr, Failed_SendInitialData);
  520.     }
  521.     
  522.     {
  523.     unsigned short    statusReturn;
  524.     
  525.     // query the device
  526.     if ((isImageWriterII) && (commType == 'SPTL') )
  527.         (**hGlobals).idleTimeout = TickCount() + kQueryTimeout;
  528.     anErr = FetchStatusString(&statusReturn, (commType == 'PPTL'), isImageWriterII);
  529.     if ( (anErr == noErr) && ( (statusReturn & kPrinterOfflineMask) != 0 )  )
  530.         anErr = gxAioTimeout;
  531.     (**hGlobals).idleTimeout = 0;
  532.     (void) GXReportStatus(kDriverStatus, kSendingData);
  533.     
  534.     // and scan the string looking for information about printer kind and options
  535.     configPtr = *configHandle;
  536.     if ( anErr == gxAioTimeout )
  537.         {
  538.         // if we timeout and we don't know the printer kind - assume IW1
  539.         if (!isImageWriterII)
  540.             {
  541.             anErr = noErr;
  542.             isImageWriterII = configPtr->isImageWriterII = false;
  543.             }
  544.         }
  545.     else
  546.         {
  547.         isImageWriterII = true;
  548.         configPtr->hasColorRibbon = (statusReturn & (0x8000 >> kColorRibbonBit)) != 0;
  549.         configPtr->hasSheetFeeder = (statusReturn & (0x8000 >> kSheetFeederBit)) != 0;
  550.         }
  551.     nrequire(anErr, FetchStatusString);
  552.     }
  553.     
  554.     // Remember if this was an ImageWriter II after the query
  555.     (**hGlobals).isImageWriterII = isImageWriterII;
  556.     
  557.     // write out the new configuration
  558.     anErr = GXWriteDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle)configHandle);
  559.     
  560.     
  561. // CLEANUP EXCEPTION HANDLING
  562. FetchStatusString:
  563. Failed_SendInitialData:
  564.     DisposHandle((Handle) configHandle);
  565.     
  566. NewHandle:
  567. Send_GXWriteData:
  568. FetchCommType:
  569.     return(anErr);
  570.     
  571. } // UpdateConfiguration
  572.  
  573.  
  574. /* ------------------------------------------------------------------------------------    */
  575. OSErr WriteDraftChars(long **draftTable, unsigned char *draftChar, long numChars)
  576. /*
  577.     This routine writes out a single character in the native set of the printer.
  578.     It uses a table that's part of the driver to do the right thing in order to generate this
  579.     character.
  580. */
  581. {
  582.     OSErr        anErr = noErr;
  583.     char        outputChars[20];                // a maximum of 20 characters can be generated
  584.     short        charCount;                    
  585.     
  586.     // For each character in the buffer, determine how to map the character to a draft character
  587.     for (; numChars > 0; --numChars, ++draftChar)
  588.     {
  589.         // No characters yet for this output character
  590.         charCount = 0;
  591.             
  592.         // Only consider characters in the printable range
  593.         if (*draftChar >= 0x20)
  594.         {
  595.             unsigned long    draftControl = (*draftTable)[*draftChar-0x20];    // Fetch native mode long word corresponding to this character
  596.             unsigned char    outChar;
  597.             unsigned char    nationalSet;
  598.             short                i;
  599.             
  600.             // For each word which composes the native mode long word 
  601.             for (i = 1; i >= 0; --i)
  602.             {
  603.                 // Should we send a backspace character (to overstrike)?
  604.                 if ( (draftControl & 0x80000000) != 0 )
  605.                     outputChars[charCount++] = 0x08;
  606.                 
  607.                 outChar = (draftControl >> 16) & 0xFF;
  608.                 if (outChar != 0)
  609.                 {
  610.                     // Determine the national character set to select
  611.                     nationalSet = (draftControl >> 24) & 0xF;    
  612.     
  613.                     //    Is this character in the standard, built-in character set?
  614.                     if (nationalSet == 0)
  615.                     {
  616.                         outputChars[charCount++] = outChar;
  617.                     }
  618.                     else    //    T => Must select a foreign language character set 
  619.                     {
  620.                         outputChars[charCount++] = 0x1B;
  621.                         outputChars[charCount++] = 0x44;
  622.                         outputChars[charCount++] = nationalSet;
  623.                         outputChars[charCount++] = 0x00;
  624.                         outputChars[charCount++] = outChar;
  625.                         outputChars[charCount++] = 0x1B;                // We always switch back to the kAmerican character set
  626.                         outputChars[charCount++] = 0x5A;
  627.                         outputChars[charCount++] = 0x07;
  628.                         outputChars[charCount++] = 0x00;
  629.                     }
  630.                 }
  631.                 
  632.                 // Take the next (low) word and process it (if we're not all done)
  633.                 draftControl <<= 16;
  634.             }    
  635.         }
  636.             
  637.         // If we generated any data, send it out now
  638.         if (charCount > 0)
  639.             anErr = Send_GXBufferData(outputChars, charCount, gxNoBufferOptions);
  640.     }
  641.         
  642.     return(anErr);    
  643.     
  644. } // WriteDraftChars
  645.  
  646. /* ------------------------------------------------------------------------------------    */
  647. OSErr GetPointerThisBig(Ptr *theBuff, long numBytes) 
  648. {
  649.     OSErr        anErr = noErr;
  650.     
  651.     if (*theBuff != nil)
  652.     {
  653.         if ( GetPtrSize(*theBuff) < numBytes )    //    T => Won't be big enough; make a new one
  654.         {
  655.             DisposPtr(*theBuff);
  656.             *theBuff = nil;
  657.         }
  658.     }
  659.  
  660.     if (*theBuff == nil)
  661.     {
  662.         *theBuff = NewPtrClear(numBytes);
  663.         anErr = MemError();
  664.     }
  665.     
  666.     return(anErr);
  667.     
  668. } // GetPointerThisBig
  669.  
  670. /* ------------------------------------------------------------------------------------    */
  671. OSErr GetTextAndPosition(    gxShape            theShape, 
  672.                             Ptr                *theChars, 
  673.                             long            *numChars, 
  674.                             gxPoint            *textPosition)
  675. {
  676.     OSErr        anErr = noErr;
  677.     long        textLength;
  678.     
  679.     // Determine the size of the text data and the position of the text
  680.     textLength = GXGetLayout(theShape, nil, nil, nil, nil, nil, nil, nil, nil, textPosition);
  681.  
  682.     // Make sure we have a buffer pointer large enough to hold all of the data
  683.     
  684.     anErr = GetPointerThisBig(theChars, textLength);
  685.     require(anErr == noErr, CantAllocTextBuff);
  686.     
  687.     // Now we retrieve the text
  688.     GXGetLayout(theShape, *theChars, nil, nil, nil, nil, nil, nil, nil, nil);
  689.     
  690.     // Remember the number of characters in the shape
  691.     *numChars = textLength;
  692.     
  693.  
  694. /******* Clean-up *******/
  695.  
  696. CantAllocTextBuff:
  697.     return(anErr);
  698.     
  699. } // GetTextAndPosition
  700.  
  701. /* ------------------------------------------------------------------------------------    */
  702. OSErr PrintPageInDraftMode(gxShape thePage, gxRasterImageDataHdl imageData)
  703. {
  704.     OSErr                    anErr = noErr;
  705.     long                    i;
  706.     long                    numItems;
  707.     Fixed                    currYPos = ff(0);
  708.     Ptr                        theChars = nil;
  709.     long                    numChars = 0;
  710.     gxPoint                    textPosition;
  711.     Fixed                    oldTextSize = ff(0);
  712.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  713.     
  714.     // Since the page picture we need to process is a picture shape that's embedded in
  715.     // thePage (a shape containing one item => a picture), we need to extract the real
  716.     // page picture from thePage.
  717.     
  718.     thePage = GetPictureItem(thePage, 1, nil, nil, nil, nil);
  719.     numItems = GXGetPicture(thePage, nil, nil, nil, nil);
  720.     
  721.     // For each shape within the picture, check its type and process it accordingly
  722.     
  723.     for (i = 1; i <= numItems; ++i)
  724.     {
  725.         gxShape                theShape;
  726.         short                theType;
  727.                 
  728.         theShape = GetPictureItem(thePage, i, nil, nil, nil, nil);
  729.         theType = GXGetShapeType(theShape);
  730.         
  731.         if (theType == gxLayoutType)    //    T => We have a layout shape
  732.         {
  733.             fixed        textSize;
  734.             char        buff[12];
  735.             char        theFace;
  736.             short        cmndBuffSz;
  737.             
  738.             // First determine the style in which we're printing
  739.             
  740.             theFace = GetStyleCommonFace( GXGetShapeStyle(theShape) );
  741.             
  742.             buff[0] = ESCAPE;
  743.             if ( (theFace & bold) != 0 )    //    T => Turn bold facing on
  744.                 buff[1] = '!';
  745.             else                                    //    T => Turn it off
  746.                 buff[1] = '"';
  747.             
  748.             buff[2] = ESCAPE;
  749.             if ( (theFace & underline) != 0 )    //    T => Turn underline facing on
  750.                 buff[3] = 'X';
  751.             else                                            //    T => Turn it off
  752.                 buff[3] = 'Y';
  753.                 
  754.             cmndBuffSz = 4;
  755.             
  756.             // Next determine if we need to change the size of the font being used
  757.             
  758.             textSize = GXGetShapeTextSize(theShape);
  759.             if (textSize != oldTextSize)    //    T => Must issue LQ command to change font size
  760.             {
  761.                 buff[4] = ESCAPE;                //    The first escape command selects black color
  762.                 buff[5] = kSetColorCommand;
  763.                 buff[6] = '0';
  764.                 
  765.                 buff[7] = ESCAPE;                //    The second escape command selects a draft font
  766.                 buff[8] = 'a';
  767.                 buff[9] = '1';
  768.                 
  769.                 buff[10] = ESCAPE;                //    The third escape command selects the character pitch
  770.                 
  771.                 if ( textSize <= ff(10) )    //    T => Select 10 cpi
  772.                 {
  773.                     buff[11] = 'N';
  774.                 }
  775.                 else    //    T => All other sizes get mapped to 12 cpi
  776.                 {
  777.                     buff[11] = 'E';
  778.                 }
  779.                 
  780.                 // Remember the last text size
  781.                 oldTextSize = textSize;    
  782.                 
  783.                 // Adjust the size of the data to be sent to the printer
  784.                 cmndBuffSz += 8;
  785.             }
  786.             // else - no change in font size
  787.             
  788.             // Send the commands to the printer
  789.             anErr = Send_GXBufferData(buff, cmndBuffSz, gxDontSplitBuffer);
  790.             require(anErr == noErr, CantSendFontCmnd);
  791.  
  792.             // Get the ASCII text and the starting position of the data
  793.             anErr = GetTextAndPosition(theShape, &theChars, &numChars, &textPosition);
  794.             require(anErr == noErr, CantGetTextAndPos);
  795.             
  796.             if ( (currYPos != ff(0)) && (currYPos != textPosition.y) )    //    T => Moving to a lower line, finish the last ;line with a CR
  797.             {
  798.                 char        c = 0x0D;
  799.                 
  800.                 anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  801.                 require(anErr == noErr, CantSendCRCmnd);
  802.             }
  803.             
  804.             // Position the print head to the proper location on the page
  805.             {
  806.                 gxMapping                theMapping;
  807.                 short                    lineFeedSize;
  808.                 Str255                    positionCmndsBuff;
  809.                 unsigned long            bytesInBuff = 0;
  810.                 char                    *p;
  811.  
  812.                 GXGetShapeMapping(theShape, &theMapping);
  813.                 MapPoints(&theMapping, (long) 1, &textPosition);    //    Just map the first point
  814.                 
  815.                 // Now position the print head vertically
  816.  
  817.                 lineFeedSize = (textPosition.y - currYPos) >> 16;
  818.                 anErr = Send_GXRasterLineFeed(&lineFeedSize, positionCmndsBuff, &bytesInBuff, imageData);
  819.                 require(anErr == noErr, CantEmitLineFeeds);
  820.                 
  821.                 // Update the current Y position pointer on the page
  822.                 currYPos = textPosition.y;
  823.  
  824.                 // Now position the print head horizontally on the page
  825.  
  826.                 p = &positionCmndsBuff[bytesInBuff];        
  827.                 *p++ = ESCAPE;
  828.                 *p++ = 'F';
  829.                 Long2Dec((*hGlobals)->leftMargin + FixedToInt(textPosition.x), p);    // Convert left margin into ASCII and place it at the start of the scan line
  830.                 
  831.                 // Update the number of bytes in the buffer
  832.                 bytesInBuff += 6;
  833.  
  834.                 // Send the positioning info to the printer
  835.                 anErr = Send_GXBufferData(positionCmndsBuff, bytesInBuff, gxDontSplitBuffer);
  836.                 require(anErr == noErr, CantSendPositionCmnds);
  837.             }
  838.             
  839.             // Now we send the text data to the printer
  840.             anErr = WriteDraftChars((long **) (*hGlobals)->draftTable, theChars, numChars);
  841.             require(anErr == noErr, CantWriteChars);
  842.         }
  843.     }    // for
  844.  
  845.     // Send one last CR to wrap the last line (if there was one)
  846.     {
  847.         char        c = 0x0D;
  848.         
  849.         anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  850.     }
  851.  
  852.  
  853. /******* Clean-up *******/
  854.  
  855. CantWriteChars:
  856. CantSendPositionCmnds:
  857. CantEmitLineFeeds:
  858. CantSendCRCmnd:
  859. CantGetTextAndPos:
  860. CantSendFontCmnd:
  861.     if (theChars != nil)
  862.         DisposPtr(theChars);
  863.                 
  864.     return(anErr);
  865.     
  866. } // PrintPageInDraftMode 
  867.  
  868. //<FF>
  869. /* ------------------------------------------------------------------------------------    */
  870. /*    SPECIFIC DRIVER UNIVERSAL OVERRIDES                                                    */
  871. /* ------------------------------------------------------------------------------------    */
  872. OSErr SD_Initialize (void) 
  873. /*
  874.     The SD_Initalize message is called when a new job is created.  The standard
  875.     thing to do is to allocate and fill out your globals as you see fit.
  876. */
  877. {
  878.  
  879.     SpecGlobalsHdl     hGlobals;
  880.     OSErr             anErr;
  881.         
  882.     // we make our globals
  883.     hGlobals = (SpecGlobalsHdl) NewHandleClear( sizeof(SpecGlobals) );
  884.     anErr = MemError();
  885.  
  886.     // and we save them away
  887.     SetMessageHandlerInstanceContext(hGlobals);
  888.  
  889.     // is everything okay?
  890.     nrequire(anErr, MNewHandleClear);
  891.     
  892.     // Don't need to initialize because of the NewHandleCLEAR
  893.     //(**hGlobals).draftTable = nil;
  894.     //(**hGlobals).lineFeeds = 0;
  895.     //(**hGlobals).packagingOptions = kNoPackagingOptions;
  896.     //(**hGlobals).idleError         = noErr;
  897.     //(**hGlobals).idleQuery         = false;
  898.     //(**hGlobals).idleTimeout         = 0;
  899.     //(**hGlobals).timeoutPending     = false;
  900.     
  901.     
  902.     return(noErr);
  903.     
  904.     
  905. /*-----EXCEPTION HANDLING------*/
  906.  
  907.  
  908. MNewHandleClear:
  909.     return(anErr);
  910.     
  911. } // SD_Initialize
  912.  
  913.  
  914. //<FF>
  915. /* ------------------------------------------------------------------------------------    */
  916. OSErr SD_ShutDown(void) 
  917. /*
  918.     Shutdown is called when the job is done with.  A good thing to do is to get
  919.     rid of any additional storage that is laying around.
  920. */
  921. {
  922.     // clean up our stuff
  923.     SpecGlobalsHdl hGlobals = GetMessageHandlerInstanceContext();
  924.  
  925.     // get rid of the draft table (if we have one)
  926.     if (hGlobals)
  927.         DisposHandle((**hGlobals).draftTable);
  928.     
  929.     // we get rid of our storage
  930.     DisposHandle((Handle) hGlobals);
  931.     
  932.     // clear out our globals - to avoid double disposes
  933.     SetMessageHandlerInstanceContext(nil);
  934.  
  935.     return(noErr);
  936.     
  937.     
  938. } // SD_ShutDown
  939.  
  940. //<FF>
  941. /* ------------------------------------------------------------------------------------    */
  942. OSErr    SD_DefaultPrinter(gxPrinter thePrinter)
  943. /*
  944.     This call is made to setup the default printer object.  The job of the
  945.     specific driver is to add in any viewDevices that it wishes applications
  946.     to be able to format specifically for.
  947. */
  948. {
  949.     OSErr            anErr;
  950.     gxViewDevice    vd;
  951.     gxJob            theJob = GXGetJob();
  952.     
  953.     // add the standard viewDevices first
  954.     anErr = Forward_GXDefaultPrinter(thePrinter);
  955.     nrequire(anErr, DefaultPrinter);
  956.     
  957.     // add a 144 b/w viewDevice
  958.     vd = NewDeviceResolutionViewDevice();
  959.     {
  960.     gxSetColor        theColors[2];
  961.     gxSetColor        *pColor;
  962.     gxColorSet        theSet;
  963.     
  964.     pColor = &theColors[0];
  965.     
  966.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0xFFFF;
  967.     
  968.     pColor++;
  969.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  970.     
  971.     theSet = GXNewColorSet(gxRGBSpace, 2, theColors);
  972.     SetViewDeviceColorSet(vd, theSet);
  973.     GXDisposeColorSet(theSet);
  974.     }
  975.         
  976.     anErr = GXAddPrinterViewDevice(thePrinter, vd);
  977.     nrequire(anErr, FailedAddBWViewDevice);
  978.  
  979.     
  980.     // add a 144 color viewDevice with 8 colors in it
  981.     //
  982.     //    Color        Index        R            G            B
  983.     //    white        0            0xFFFF        0xFFFF        0xFFFF        
  984.     //    yellow        1            0xFFFF        0xFFFF        0x0000
  985.     //    magenta        2            0xFFFF        0x0000        0xFFFF
  986.     //    red            3            0xFFFF        0x0000        0x0000
  987.     //    cyan        4            0x0000        0xFFFF        0xFFFF
  988.     //    green        5            0x0000        0xFFFF        0x0000
  989.     //    blue        6            0x0000        0x0000        0xFFFF
  990.     //    black        7            0x0000        0x0000        0x0000
  991.     
  992.     if (PrinterHasColorRibbon(thePrinter))
  993.         {
  994.         gxSetColor        theColors[8];
  995.         gxSetColor        *pColor;
  996.         gxColorSet        theSet;
  997.         short            idx;
  998.  
  999.         vd = NewDeviceResolutionViewDevice();
  1000.         
  1001.         pColor = &theColors[0];
  1002.         for (idx = 0; idx < 8; ++idx)
  1003.             {
  1004.             // default the color to black
  1005.             pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  1006.             
  1007.             // and give it componants to go along with this index
  1008.             if (idx & 0x04)
  1009.                 pColor->rgb.red     = 0xFFFF;
  1010.             if (idx & 0x02)
  1011.                 pColor->rgb.green     = 0xFFFF;
  1012.             if (idx & 0x01)
  1013.                 pColor->rgb.blue     = 0xFFFF;
  1014.                 
  1015.             // move on to the next color
  1016.             ++pColor;
  1017.             }
  1018.         
  1019.         theSet = GXNewColorSet(gxRGBSpace, 8, theColors);
  1020.         SetViewDeviceColorSet(vd, theSet);
  1021.         GXDisposeColorSet(theSet);
  1022.  
  1023.         anErr = GXAddPrinterViewDevice(thePrinter, vd);
  1024.         nrequire(anErr, FailedAddColorViewDevice);
  1025.         }
  1026.     
  1027.     /* Only if we are the output printer (not the formatting printer) */
  1028.     if (GXGetJobPrinter(theJob) == GXGetJobOutputPrinter(theJob)) {
  1029.         Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1030.         Handle                 jobQualitySettingsHdl;    
  1031.         gxQualityInfo        *qualitySettings;
  1032.         Ptr                    p;
  1033.         Str255                bestString, roughString;
  1034.  
  1035.         // read in our quality mode strings
  1036.         {
  1037.         short    curResFile = CurResFile();
  1038.         
  1039.         UseResFile(GXGetMessageHandlerResFile());
  1040.         
  1041.         GetIndString( bestString, kNewQualityID, kBestString);
  1042.         GetIndString( roughString, kNewQualityID, kRoughString);
  1043.         UseResFile(curResFile);
  1044.         }
  1045.         
  1046.         jobQualitySettingsHdl = NewHandle(0);
  1047.         anErr = MemError();
  1048.         nrequire(anErr, FailedNewHandle);
  1049.  
  1050.         anErr = GetCollectionItemHdl (     jobCollection,
  1051.                                         gxQualityTag,
  1052.                                         gxPrintingTagID,
  1053.                                         jobQualitySettingsHdl );
  1054.  
  1055.         if (anErr == noErr) 
  1056.             {    /* Check for proper structure -- count as not found if different */
  1057.             HLockHi(jobQualitySettingsHdl);
  1058.  
  1059.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1060.             p = qualitySettings->qualityNames;
  1061.  
  1062.             if (qualitySettings->disableQuality) 
  1063.                 anErr = collectionItemNotFoundErr;
  1064.             else if (qualitySettings->qualityCount != 2)
  1065.                 anErr = collectionItemNotFoundErr;
  1066.             else if (! IUEqualString(p, bestString))
  1067.                 anErr = collectionItemNotFoundErr;
  1068.             else if (! IUEqualString(p + p[0] + 1, roughString))
  1069.                 anErr = collectionItemNotFoundErr;
  1070.  
  1071.             HUnlock(jobQualitySettingsHdl);
  1072.             }
  1073.  
  1074.         if (anErr == collectionItemNotFoundErr) 
  1075.             {
  1076.             Size            count;
  1077.  
  1078.             /* Create the proper quality item */
  1079.             SetHandleSize(jobQualitySettingsHdl,(sizeof(gxQualityInfo) + bestString[0] + roughString[0] + 2 ));
  1080.             anErr = MemError();
  1081.             nrequire( anErr, FailedSetHandleSize );
  1082.                 
  1083.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1084.             
  1085.             qualitySettings->disableQuality = false;
  1086.             qualitySettings->defaultQuality = 1;
  1087.             qualitySettings->currentQuality = 1;
  1088.             qualitySettings->qualityCount = 2;
  1089.  
  1090.             count = bestString[0]+1;
  1091.             p = qualitySettings->qualityNames;
  1092.             BlockMove( bestString, p, count );
  1093.  
  1094.             p += count;
  1095.             BlockMove( roughString, p, roughString[0]+1 );
  1096.  
  1097.             /* Add the proper quality item */
  1098.             anErr = AddCollectionItemHdl (     jobCollection,
  1099.                                             gxQualityTag,
  1100.                                             gxPrintingTagID,
  1101.                                             jobQualitySettingsHdl );
  1102.  
  1103.             /* Make it vilatile by driver */
  1104.             if (anErr == noErr)
  1105.                 (void) SetCollectionItemInfo(jobCollection, gxQualityTag, gxPrintingTagID, 0x0000FFFF, gxVolatileOutputDriverCategory);
  1106.  
  1107.             }
  1108.         
  1109. FailedSetHandleSize:
  1110.         DisposHandle(jobQualitySettingsHdl);
  1111.     }
  1112. FailedNewHandle:
  1113.     
  1114.     ncheck(noErr);
  1115.     return(noErr);
  1116.     
  1117.     
  1118.     
  1119. // EXCEPTION HANDLING
  1120. FailedAddColorViewDevice:
  1121. FailedAddBWViewDevice:
  1122.     GXDisposeViewDevice(vd);
  1123.     
  1124. DefaultPrinter:
  1125.     return(anErr);
  1126.     
  1127. } // SD_DefaultPrinter
  1128.  
  1129. //<FF>
  1130. /* ------------------------------------------------------------------------------------    */
  1131.  
  1132. OSErr SD_DefaultFormat(gxFormat theFormat)
  1133. {
  1134.     OSErr                anErr;
  1135.     Handle                 jobQualitySettingsHdl;    
  1136.     
  1137.     anErr = Forward_GXDefaultFormat(theFormat);
  1138.     
  1139.     // now, if the application has set up a special formatting mode, we need to update
  1140.     // the quality mode collection item (and any private ones we use)
  1141.     if (anErr == noErr)
  1142.         {
  1143.         gxPoint                dpiPoint = {ff(72), ff(72)};
  1144.         gxMapping            vdMapping;
  1145.         gxViewDevice        selectedDevice = GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 0);
  1146.         
  1147.         if (selectedDevice != GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 1) )
  1148.             {
  1149.             GXGetViewDeviceMapping(selectedDevice, &vdMapping);
  1150.             MapPoints(&vdMapping, 1, &dpiPoint);
  1151.             
  1152.             {
  1153.             Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1154.             gxQualityInfo        *qualitySettings;
  1155.     
  1156.             jobQualitySettingsHdl = NewHandle(0);
  1157.             anErr = MemError();
  1158.             nrequire(anErr, FailedNewHandle);
  1159.  
  1160.             anErr = GetCollectionItemHdl (     jobCollection,
  1161.                                                 gxQualityTag,
  1162.                                                  gxPrintingTagID,
  1163.                                                jobQualitySettingsHdl );
  1164.  
  1165.             nrequire(anErr, FailedGetCollectionItemHdl);
  1166.  
  1167.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1168.  
  1169.             qualitySettings->currentQuality = 
  1170.                 (dpiPoint.y > ff(100)) ? (qualitySettings->qualityCount-1) : 0;
  1171.  
  1172.             anErr = AddCollectionItemHdl (     jobCollection,
  1173.                                             gxQualityTag,
  1174.                                             gxPrintingTagID,
  1175.                                             jobQualitySettingsHdl );
  1176.                                                  
  1177.             DisposHandle(jobQualitySettingsHdl);
  1178.             }
  1179.  
  1180.         
  1181.             if (anErr == noErr)
  1182.                 {
  1183.                 long    formatOptions;
  1184.                 
  1185.                 // turn off super-res
  1186.                 formatOptions = 0;
  1187.                 anErr = AddCollectionItem(GXGetFormatCollection(theFormat), 
  1188.                     DriverCreator, 0,
  1189.                     sizeof(formatOptions),
  1190.                     &formatOptions);
  1191.                 }
  1192.             }
  1193.         }
  1194.  
  1195. FailedNewHandle:        
  1196.     ncheck(anErr);
  1197.     return(anErr);
  1198.  
  1199. FailedGetCollectionItemHdl:
  1200.     DisposHandle(jobQualitySettingsHdl);
  1201.     return(anErr);
  1202.     
  1203. } // SD_DefaultFormat
  1204.  
  1205. //<FF>
  1206. /* ------------------------------------------------------------------------------------    */
  1207. OSErr SD_DefaultJob()
  1208. /*
  1209.     We override this message to add our default - highest res possible
  1210. */
  1211. {
  1212.     OSErr    anErr;
  1213.     
  1214.     anErr = Forward_GXDefaultJob();
  1215.     if (anErr == noErr)
  1216.         {
  1217.         long        imagewriterOptions = kSuperRes;
  1218.         
  1219.         anErr = AddCollectionItem(GXGetJobCollection(GXGetJob()), 
  1220.                     DriverCreator,
  1221.                     0,
  1222.                     sizeof(imagewriterOptions),
  1223.                     &imagewriterOptions);
  1224.                     
  1225.         }
  1226.  
  1227.  
  1228.     return(anErr);
  1229.     
  1230. } // SD_DefaultJob
  1231.  
  1232. /* ------------------------------------------------------------------------------------    */
  1233. OSErr SD_OpenConnection(void)
  1234. /*
  1235.     The OpenConnection message is sent in order to open the connection to the device.
  1236. */
  1237. {
  1238.     OSErr    anErr;
  1239.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1240.     
  1241.     // how to process idle events
  1242.     (**hGlobals).idleError         = noErr;
  1243.     (**hGlobals).idleQuery         = false;
  1244.     (**hGlobals).idleTimeout     = 0;
  1245.     (**hGlobals).timeoutPending = false;
  1246.     
  1247.     // first, open the connection the standard way
  1248.     anErr = Forward_GXOpenConnection();
  1249.     nrequire(anErr, OpenConnection);
  1250.     
  1251.     // then, bring the configuration file up to date
  1252.     anErr = UpdateConfiguration();
  1253.     nrequire(anErr, UpdateConfiguration);
  1254.     
  1255.     return(noErr);
  1256.     
  1257. // EXCEPTION HANDLING
  1258. UpdateConfiguration:
  1259.     GXCleanupOpenConnection();
  1260.     
  1261. OpenConnection:
  1262.  
  1263.     return(anErr);
  1264.     
  1265. } // SD_OpenConnection
  1266.  
  1267. /* ------------------------------------------------------------------------------------    */
  1268. OSErr SD_CloseConnection(void)
  1269. {
  1270.     unsigned short    statusReturn;
  1271.     OSErr            anErr, anErr2;
  1272.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1273.     ResType            commType = (**hGlobals).commType;
  1274.  
  1275.     if (commType == 'PPTL')
  1276.         {
  1277.         // flush out all data so that we can query the printer properly    one last time
  1278.         anErr = Send_GXWriteData(nil, 0);
  1279.         nrequire(anErr, Send_GXWriteData1);
  1280.         
  1281.         // for PAP: bring the configuration file up to date & check that the printer is online
  1282.         anErr2 = UpdateConfiguration();
  1283.         if (anErr == noErr) anErr = anErr2;
  1284.         }
  1285.     else
  1286.         {
  1287.         // for serial: flush out all data so that we can query the printer properly    one last time
  1288.         anErr = Send_GXWriteData(nil, 0);
  1289.         nrequire(anErr, Send_GXWriteData2);
  1290.  
  1291.         // one last time check up on printer status 
  1292.         if ((**hGlobals).isImageWriterII)
  1293.             {
  1294.             anErr2 = FetchStatusString(&statusReturn, false, true);
  1295.             if (anErr == noErr) anErr = anErr2;
  1296.             }
  1297.         }
  1298.     
  1299. Send_GXWriteData2:
  1300. Send_GXWriteData1:
  1301. FetchStatusString:
  1302.     // close the connection the standard way
  1303.     anErr2 = Forward_GXCloseConnection();
  1304.     if (anErr == noErr) anErr = anErr2;
  1305.         
  1306.     return(anErr);
  1307.     
  1308. } // SD_CloseConnection
  1309.  
  1310. /* ------------------------------------------------------------------------------------    */
  1311. OSErr SD_JobIdle()
  1312. {
  1313.     OSErr            anErr = noErr;
  1314.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1315.     SpecGlobalsPtr    pGlobals;
  1316.     
  1317.     pGlobals = *hGlobals;
  1318.     if ( (pGlobals->idleQuery) && (pGlobals->commType == 'PPTL') )
  1319.         {
  1320.         unsigned short    statusReturn;
  1321.  
  1322.         pGlobals->idleQuery = false;
  1323.         
  1324.         anErr = FetchStatusString(&statusReturn, true, true);
  1325.         nrequire(anErr, FetchStatusString);
  1326.  
  1327.         anErr = Forward_GXJobIdle();
  1328.  
  1329.         // EXCEPTION HANDLING
  1330.         FetchStatusString:
  1331.             pGlobals = *hGlobals;
  1332.             pGlobals->idleQuery = true;
  1333.         }
  1334.     else    
  1335.         anErr = Forward_GXJobIdle();
  1336.     
  1337.     // if we continue looping here too long during the initial query -- give the user
  1338.     // a chance to bail or correct the problem
  1339.     pGlobals = *hGlobals;
  1340.     if ( (!(pGlobals->timeoutPending)) && (pGlobals->idleTimeout != 0) )
  1341.         {
  1342.         if (TickCount() > pGlobals->idleTimeout)
  1343.             {
  1344.             gxStatusRecord        theStat;
  1345.             gxStatusRecord        *pStat = &theStat;
  1346.             
  1347.             pStat->statusOwner    = 'drvr';
  1348.             pStat->statResId     = kDriverStatus;        
  1349.             pStat->statResIndex = kCheckOnline;            
  1350.             pStat->bufferLen      = 0;
  1351.             pStat->dialogResult = nil;
  1352.                         
  1353.             // tell the user to check the printer
  1354.             pGlobals->timeoutPending = true;
  1355.             (void) GXAlertTheUser(pStat);
  1356.             pGlobals = *hGlobals;
  1357.             pGlobals->timeoutPending = false;
  1358.                 
  1359.             // based on the user's response cancel
  1360.             switch (pStat->dialogResult)
  1361.                 {
  1362.                 case ok:
  1363.                     pGlobals->idleTimeout = TickCount() + kQueryTimeout;
  1364.                     break;
  1365.                     
  1366.                 case cancel:
  1367.                     pGlobals->idleError = gxPrUserAbortErr;
  1368.                     break;
  1369.                     
  1370.                 case 3:
  1371.                     pGlobals->idleError = kPutJobOnHoldErr;
  1372.                     break;
  1373.                 }
  1374.  
  1375.             // display "sending data to the printer" message
  1376.             if (anErr == noErr)
  1377.                 anErr = GXReportStatus(kDriverStatus, kSendingData);
  1378.             }
  1379.         }
  1380.         
  1381.     if (anErr == noErr)
  1382.         anErr = pGlobals->idleError;
  1383.         
  1384.     return(anErr);
  1385.     
  1386. } // SD_JobIdle
  1387.  
  1388. /* ------------------------------------------------------------------------------------    */
  1389. OSErr SD_FreeBuffer(gxPrintingBuffer * theBuffer)
  1390. {
  1391.     OSErr            anErr = noErr;
  1392.     OSErr            firstError = noErr;
  1393.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1394.     
  1395.  
  1396.     if ((**hGlobals).commType == 'PPTL')
  1397.         {
  1398.         unsigned short    statusReturn;
  1399.  
  1400.         anErr = FetchStatusString(&statusReturn, true, true);
  1401.         nrequire(anErr, FetchStatusString);
  1402.         }
  1403.         
  1404.     do
  1405.         {
  1406.         // we can idle query now if we need to    
  1407.         (**hGlobals).idleQuery = true;
  1408.  
  1409.         // try to send the buffer again
  1410.         anErr = Forward_GXFreeBuffer(theBuffer);
  1411.         if (firstError == noErr)
  1412.             firstError = anErr;
  1413.     
  1414.         (**hGlobals).idleQuery = false;
  1415.  
  1416.         // timeout dialog!
  1417.         if (anErr == gxAioTimeout)
  1418.             {
  1419.             gxStatusRecord        theStat;
  1420.             gxStatusRecord        *pStat = &theStat;
  1421.             
  1422.             pStat->statusOwner    = 'drvr';
  1423.             pStat->statResId     = kDriverStatus;        
  1424.             pStat->statResIndex = kCheckOnline;            
  1425.             pStat->bufferLen      = 0;
  1426.             pStat->dialogResult = nil;
  1427.                         
  1428.             // tell the user to check the printer
  1429.             (void) GXAlertTheUser(pStat);
  1430.                 
  1431.             // based on the user's response cancel
  1432.             switch (pStat->dialogResult)
  1433.                 {
  1434.                 case ok:
  1435.                     anErr = gxAioTimeout;
  1436.                     break;
  1437.                     
  1438.                 case cancel:
  1439.                     anErr = gxPrUserAbortErr;
  1440.                     break;
  1441.                     
  1442.                 case 3:
  1443.                     anErr = kPutJobOnHoldErr;
  1444.                     break;
  1445.                 }
  1446.             }
  1447.             
  1448.         } while (anErr == gxAioTimeout);
  1449.     
  1450.     // put down the timeout dialog, if we ever put one up
  1451.     if (firstError != noErr)
  1452.         (void) GXReportStatus(kDriverStatus, kSendingData);
  1453.  
  1454.     // error to return from next idle
  1455.     (**hGlobals).idleError = anErr;
  1456.     
  1457. FetchStatusString:        
  1458.     return(anErr);
  1459.     
  1460. } // SD_FreeBuffer
  1461.  
  1462. /* ------------------------------------------------------------------------------------    */
  1463. OSErr SD_DumpBuffer(gxPrintingBuffer * theBuffer)
  1464. {
  1465.     OSErr    anErr;
  1466.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1467.         
  1468.     if ((**hGlobals).commType == 'PPTL')
  1469.         {
  1470.         unsigned short    statusReturn;
  1471.         anErr = FetchStatusString(&statusReturn, true, true);
  1472.         nrequire(anErr, FetchStatusString);
  1473.         }
  1474.     anErr = Forward_GXDumpBuffer(theBuffer);
  1475.  
  1476. FetchStatusString:        
  1477.     return(anErr);
  1478.     
  1479. } // SD_DumpBuffer
  1480.  
  1481. /* ------------------------------------------------------------------------------------    */
  1482. OSErr SD_StartSendPage(gxFormat pageFormat)
  1483. /*
  1484.     The StartSendPage message is sent just before the page begins to be rendered.
  1485.     
  1486.     Note that the StartSendPage message will not be sent until imaging/communication
  1487.     time, so that user interaction alerts are considered okay here
  1488. */
  1489. {
  1490.     OSErr                        anErr = noErr;
  1491.     gxJob                        theJob = GXGetJob();
  1492.     Collection                    jobCollection;
  1493.     gxPaperType                    thePaperType;
  1494.     gxTrayFeedInfo                trayFeedInfo;
  1495.     long                        itemSize = sizeof(trayFeedInfo);
  1496.     ResType                        commType;
  1497.     unsigned short                statusReturn;
  1498.     
  1499.     check(theJob);
  1500.     jobCollection = GXGetJobCollection(theJob);
  1501.     check(jobCollection);
  1502.     
  1503.     // cache communications type
  1504.     commType = (**(SpecGlobalsHdl)GetMessageHandlerInstanceContext()).commType;
  1505.     if (commType == 'PPTL')
  1506.         {
  1507.         anErr = FetchStatusString(&statusReturn, true, true);
  1508.         nrequire(anErr, FetchStatusString);
  1509.         }
  1510.     else
  1511.         statusReturn = 0;
  1512.         
  1513.     // check to see if this particular page is to be manually fed
  1514.     anErr = GetCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, &itemSize, &trayFeedInfo);
  1515.     nrequire(anErr, FailedGetCollectionItem);
  1516.             
  1517.     // manual feed or out of paper?  Time to ask the user what to do
  1518.     if     (     trayFeedInfo.manualFeedThisPage
  1519.         ||  ( ( (statusReturn & kOutOfPaperMask) != 0 ) )
  1520.         )
  1521.         {
  1522.         // Wait for all IO to complete, so that we can correctly tell the user what to do.
  1523.         // Since the WriteData message makes sure all data is flushed before performing the
  1524.         // IO, this call insures that pending IO is complete.
  1525.         anErr = Send_GXWriteData(nil, 0);
  1526.         nrequire(anErr, FlushAllData);
  1527.  
  1528.  
  1529.         // then, conduct the alert with the user
  1530.         {
  1531.         gxStatusRecord        *pStat;
  1532.         
  1533.         // make a status record containing the request to the user - note that 
  1534.         // we have to make room for ManualFeedRecord OR OutOfPaperRecord, but manual is bigger
  1535.         pStat = (gxStatusRecord *)NewPtrClear(sizeof(gxStatusRecord)  + sizeof(gxManualFeedRecord));
  1536.         anErr = MemError();
  1537.         nrequire(anErr, NewPtrClear);
  1538.                 
  1539.         pStat->statusOwner    = 'univ';
  1540.         pStat->statResId     = gxUnivAlertStatusResourceId;    // we use the built-in status for this
  1541.         pStat->dialogResult = nil;
  1542.         
  1543.         if (trayFeedInfo.manualFeedThisPage)
  1544.             {
  1545.             gxManualFeedRecord    *pFeed;
  1546.             
  1547.             pStat->statResIndex = gxUnivManualFeedIndex;            // status meaning "manual feed alert"
  1548.             pStat->bufferLen      = sizeof(gxManualFeedRecord);
  1549.             pFeed = (gxManualFeedRecord*)&pStat->statusBuffer;
  1550.         
  1551.             // we can switch to autofeed if we want - and tell the user what kind of paper to load in
  1552.             pFeed->canAutoFeed = true;
  1553.             GXGetPaperTypeName(thePaperType = GXGetFormatPaperType(pageFormat), pFeed->paperTypeName);
  1554.             }
  1555.         else
  1556.             {
  1557.             gxOutOfPaperRecord    *pOut;
  1558.             
  1559.             pStat->statResIndex = gxUnivOutOfPaperIndex;            // status meaning "manual feed alert"
  1560.             pStat->bufferLen      = sizeof(gxOutOfPaperRecord);
  1561.             
  1562.             pOut = (gxOutOfPaperRecord*)&pStat->statusBuffer;
  1563.             GXGetPaperTypeName(GXGetFormatPaperType(pageFormat), pOut->paperTypeName);
  1564.             }
  1565.             
  1566.         // keep sending the user the alert until either
  1567.         //  a) the problem resolves itself
  1568.         //  b) the user responds via the dialog
  1569.         //  c) some other (fatal) error happens
  1570.         do
  1571.             {
  1572.             
  1573.             // tell the user
  1574.             anErr = GXAlertTheUser(pStat);
  1575.             
  1576.             // if the paper got suddenly loaded, do an OK
  1577.             if (commType == 'PPTL')
  1578.                 {
  1579.                 (void) FetchStatusString(&statusReturn, true, true);
  1580.                 if ((statusReturn & kOutOfPaperMask) == 0)
  1581.                     {
  1582.                     pStat->dialogResult = ok;
  1583.                     anErr = noErr;
  1584.                     }
  1585.                 }
  1586.                 
  1587.             } while ((anErr == noErr) && (pStat->dialogResult == nil));
  1588.  
  1589.         // based on the user's response, continue, cancel, or switch to auto feed
  1590.         switch ( pStat->dialogResult )
  1591.             {
  1592.             case ok:
  1593.                 // paper is loaded
  1594.                 break;
  1595.                 
  1596.             case cancel:
  1597.                 // user wishes to stop the printing process
  1598.                 anErr = gxPrUserAbortErr;
  1599.                 break;
  1600.                 
  1601.             case gxAutoFeedButtonId:
  1602.                 // do rest of job with auto feed
  1603.                 
  1604.                 {
  1605.                 gxPaperFeedInfo paperFeed;
  1606.                 
  1607.                 /* Update for job */
  1608.                 paperFeed.autoFeed = true;
  1609.                 (void) AddCollectionItem(jobCollection, gxPaperFeedTag, gxPrintingTagID, sizeof(paperFeed), &paperFeed);
  1610.                 }
  1611.                 
  1612.                 /* Update as it may be reused */
  1613.                 trayFeedInfo.manualFeedThisPage = false;    /* Other trayInfo fields are still valid */
  1614.                 (void) AddCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, sizeof(trayFeedInfo), &trayFeedInfo);
  1615.                 
  1616.                 /* Can pass paper type reference as this IS device communication time */
  1617.                 anErr = Send_GXCheckStatus((Ptr) &thePaperType, sizeof(thePaperType), 0, 'univ');
  1618.                 ncheck(anErr);
  1619.                 
  1620.                 /* No need to reset tray from gxTrayFeedInfo.feedTrayIndex as there is only one tray! */
  1621.                 break;
  1622.                 
  1623.             } // switch
  1624.             
  1625.             
  1626.         // done with the status now
  1627.         DisposPtr((Ptr) pStat);
  1628.         }
  1629.             
  1630.         } // if manual feed job
  1631.         
  1632.     // display "sending data to the printer" message
  1633.     if (anErr == noErr)
  1634.         anErr = GXReportStatus(kDriverStatus, kSendingData);
  1635.         
  1636.     nrequire(anErr, FailedWaitForPaper);
  1637.         
  1638.     // continue with the standard starting of the page
  1639.     anErr = Forward_GXStartSendPage(pageFormat);
  1640.         
  1641.         
  1642. // FALL THROUGH AND HANDLE EXCEPTIONS
  1643.  
  1644. FailedWaitForPaper:
  1645. NewPtrClear:
  1646. FlushAllData:
  1647. FailedGetCollectionItem:
  1648. FetchStatusString:
  1649.     return(anErr);
  1650.     
  1651. } // SD_StartSendPage
  1652.  
  1653. /* ------------------------------------------------------------------------------------    */
  1654. OSErr SD_FinishSendPage()
  1655. {
  1656.     OSErr        anErr = noErr;
  1657.     Str63        formLength;            // should be more than big enough for form skipping
  1658.     char        len = 0;
  1659.  
  1660.     // we may have issued line feeds RIGHT up to the end of the page.  If
  1661.     // we do that and then issue a form feed, we'll kick out a blank page.
  1662.     // to avoid that, we back up a tad and then let the normal form feed
  1663.     // go through.  Option 2 would be to track each and every motion control
  1664.     // we send to the printer -- but that's more work than this.  In addition,
  1665.     // this method makes sure we are synced up exactly to the hardware
  1666.     formLength[len++] = ESCAPE;
  1667.     formLength[len++] = 'T';
  1668.     formLength[len++] = '0';
  1669.     formLength[len++] = '1';
  1670.     formLength[len++] = ESCAPE;
  1671.     formLength[len++] = 'r';
  1672.     formLength[len++] = 0x0A;
  1673.     
  1674.     // reset to forward motion for the form feed
  1675.     formLength[len++] = ESCAPE;
  1676.     formLength[len++] = 'f';
  1677.     
  1678.     anErr = Send_GXBufferData(&formLength[0], len, gxNoBufferOptions );
  1679.     nrequire(anErr, Send_GXBufferData);
  1680.     
  1681.     // Default implementation provides the actual form feed
  1682.     anErr = Forward_GXFinishSendPage();
  1683.     
  1684. // FALL THROUGH EXCEPTION HANDLING
  1685. Send_GXBufferData:
  1686.  
  1687.     return(anErr);
  1688.     
  1689. } // SD_FinishSendPage
  1690.  
  1691. /* ------------------------------------------------------------------------------------    */
  1692. OSErr SD_JobFormatDialog(gxDialogResult*    theResult)
  1693. /*
  1694.     This message is sent in response to the user's request to put up a formatting dialog
  1695. */
  1696. {
  1697.     OSErr                     anErr;
  1698.     gxJobFormatModeTableHdl    theJobFormatModeList;
  1699.     long                    i;
  1700.     gxJob                     theJob = GXGetJob();
  1701.     
  1702.     // set up the JobFormatMode information
  1703.     
  1704.     anErr = GXGetAvailableJobFormatModes(&theJobFormatModeList);
  1705.     if ((!anErr) && (theJobFormatModeList))
  1706.         {
  1707.         for (i = 0; i <= (*theJobFormatModeList)->numModes - 1; ++i) 
  1708.             {
  1709.             if ((*theJobFormatModeList)->modes[i] == gxTextJobFormatMode) 
  1710.                 {
  1711.                 GXSetPreferredJobFormatMode(gxTextJobFormatMode, false);
  1712.                 break;
  1713.                 }
  1714.             }
  1715.         DisposHandle((Handle)theJobFormatModeList);
  1716.         }
  1717.         
  1718.     // do the normal dialogs after handling the job format mode stuff
  1719.     return(Forward_GXJobDefaultFormatDialog(theResult));
  1720.     
  1721. } // SD_JobFormatModeQuery
  1722.  
  1723. /* ------------------------------------------------------------------------------------    */
  1724. OSErr SD_JobFormatModeQuery(    gxQueryType        theQuery,
  1725.                                 void*            srcData,
  1726.                                 void*            dstData)
  1727. /*
  1728.     This message is sent to find out information about the current job format mode.
  1729. */
  1730. {
  1731.     OSErr        anErr = noErr;
  1732.     Handle        theFonts;
  1733.     Handle        theStyles;
  1734.     
  1735.     check(dstData != nil);
  1736.     
  1737.     // What type of query is being requested?
  1738.     switch(theQuery) 
  1739.     {
  1740.         case gxSetStyleJobFormatCommonStyleQuery:
  1741.         {
  1742.             char                *pStyleName;
  1743.  
  1744.             // Fetch the list of supported styles
  1745.             
  1746.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1747.             require(anErr == noErr, FailedToLoadStyles1);
  1748.             
  1749.             HNoPurge(theStyles);
  1750.             HLock(theStyles);
  1751.             
  1752.             // Determine which style is being referenced and set the corresponding style (only 2 styles
  1753.             // are currently supported)
  1754.             
  1755.             if (**((short **) theStyles) == 2)    //    T => We have the correct number of styles
  1756.             {
  1757.                 char        whichFace = 0;
  1758.                 
  1759.                 pStyleName = ((char *) *theStyles) + sizeof(short); 
  1760.                 
  1761.                 if ( IUCompString(pStyleName, (char *) srcData) == 0 )    //    T => They want bold face
  1762.                 {
  1763.                     whichFace = bold;
  1764.                 }
  1765.                 else
  1766.                 {
  1767.                     // Point to the next name in the list
  1768.                     pStyleName += *pStyleName + 1;
  1769.  
  1770.                     if ( IUCompString(pStyleName, (char *) srcData) == 0 )    //    T => They want underline face
  1771.                     {
  1772.                         whichFace = underline;
  1773.                     }
  1774.                 }
  1775.  
  1776.                 //    If the client specified a valid face, set it now
  1777.                 if (whichFace != 0)
  1778.                 {
  1779.                     SetStyleCommonFace((gxStyle) dstData, GetStyleCommonFace((gxStyle) dstData) | whichFace);
  1780.                 }
  1781.             }
  1782.             // else - something is wrong with our resource
  1783.             
  1784.             // Dump the temporary handle
  1785.             DisposHandle(theStyles);
  1786.             
  1787.             break;
  1788.         }
  1789.             
  1790.         case gxGetJobFormatFontCommonStylesQuery:
  1791.         {
  1792.             short                numStyles;
  1793.             short                i;
  1794.             char                *pStyleName;
  1795.  
  1796.             // Fetch the list of supported styles
  1797.             
  1798.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1799.             require(anErr == noErr, FailedToLoadStyles2);
  1800.             
  1801.             HNoPurge(theStyles);
  1802.             HLock(theStyles);
  1803.             
  1804.             // Determine the number of styles in the list
  1805.             numStyles = **((short **) theStyles);
  1806.  
  1807.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the styles
  1808.                 SetHandleSize(*(Handle *)dstData, sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1809.             else
  1810.                 *(Handle *)dstData = NewHandle(sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1811.             
  1812.             anErr = MemError();
  1813.             require(anErr == noErr, StyleTableResizeFailed);
  1814.             
  1815.             // Now extract the name of each of the supported fonts
  1816.             
  1817.             for (i = 1, pStyleName = ((char *) *theStyles) + sizeof(short); i <= numStyles; ++i, pStyleName += *pStyleName + 1)
  1818.             {
  1819.                 BlockMove(pStyleName, (*((gxStyleNameTableHdl) *(Handle *)dstData))->styleNames[i - 1], *pStyleName + 1);
  1820.             }
  1821.             
  1822.             (*((gxStyleNameTableHdl) *(Handle *)dstData))->numStyleNames = numStyles;
  1823.             
  1824.             // Dump the temporary handle
  1825.             DisposHandle(theStyles);
  1826.             
  1827.             break;
  1828.         }
  1829.             
  1830.         case gxGetJobFormatLineConstraintQuery:            //    This type of query is not supported
  1831.             if (*(Handle *)dstData != nil)
  1832.                 SetHandleSize(*(Handle *)dstData, 0);        // Don't return any data
  1833.             break;
  1834.             
  1835.         case gxGetJobFormatFontsQuery:
  1836.         {
  1837.             short                numFonts;
  1838.             short                i;
  1839.             char                *pFontName;
  1840.  
  1841.             // Fetch the list of supported fonts
  1842.             
  1843.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeFontsID, &theFonts);
  1844.             require(anErr == noErr, FailedToLoadFonts);
  1845.             
  1846.             HNoPurge(theFonts);
  1847.             HLock(theFonts);
  1848.             
  1849.             // Determine the number of fonts in the list
  1850.             numFonts = **((short **) theFonts);
  1851.  
  1852.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the fonts
  1853.                 SetHandleSize(*(Handle *)dstData, sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1854.             else
  1855.                 *(Handle *)dstData = NewHandle(sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1856.             
  1857.             anErr = MemError();
  1858.             require(anErr == noErr, FontTableResizeFailed);
  1859.             
  1860.             // Now generate a reference to each of the supported fonts
  1861.             
  1862.             for (i = 1, pFontName = ((char *) *theFonts) + sizeof(short); i <= numFonts; ++i, pFontName += *pFontName + 1)
  1863.             {
  1864.                 gxFont            thisFont;
  1865.                 gxFontTable        *pFontTable;
  1866.             
  1867.                 thisFont = FindPNameFont(gxFullFontName, pFontName);
  1868.                 
  1869.                 pFontTable = *((gxFontTableHdl) *(Handle *)dstData);
  1870.                 pFontTable->fonts[i - 1] = thisFont;
  1871.             }
  1872.             
  1873.             (*((gxFontTableHdl) *(Handle *)dstData))->numFonts = numFonts;
  1874.             
  1875.             // Dump the temporary handle
  1876.             DisposHandle(theFonts);
  1877.  
  1878.             break;
  1879.         }
  1880.             
  1881.         case gxGetJobFormatFontConstraintQuery:
  1882.         {
  1883.             gxPositionConstraintTable        *pPositionTable;
  1884.             
  1885.             if ( *(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on position constraints
  1886.                 SetHandleSize(*(Handle *)dstData, sizeof(gxPositionConstraintTable) + sizeof(Fixed));
  1887.             else
  1888.                 *(Handle *)dstData = NewHandle( sizeof(gxPositionConstraintTable) + sizeof(Fixed) );
  1889.             
  1890.             pPositionTable = *((gxPositionConstraintTableHdl) *(Handle *)dstData);
  1891.             
  1892.             pPositionTable->phase.x     = 0;                //    Start at the top left corner of the page
  1893.             pPositionTable->phase.y     = 0;
  1894.             pPositionTable->offset.x     = ff(12);        // Indent from the top left by a six lines per inch margin
  1895.             pPositionTable->offset.y     = ff(12);         
  1896.             pPositionTable->numSizes     = 2;                // Two font sizes supported
  1897.             pPositionTable->sizes[0]     = ff(10);         // 10 pitch
  1898.             pPositionTable->sizes[1]     = ff(12);         // 12 pitch
  1899.             
  1900.             break;
  1901.         }
  1902.     } // switch
  1903.     
  1904.     return(anErr);
  1905.     
  1906.  
  1907. /******* Clean-up *******/
  1908.  
  1909. StyleTableResizeFailed:
  1910.     DisposHandle((Handle) theStyles);
  1911.     return(anErr);
  1912.  
  1913. FontTableResizeFailed:
  1914.     DisposHandle((Handle) theFonts);
  1915.  
  1916. FailedToLoadStyles1:
  1917. FailedToLoadStyles2:
  1918. FailedToLoadFonts:
  1919.     return(anErr);
  1920.     
  1921. } // SD_JobFormatModeQuery
  1922.  
  1923. //<FF>
  1924. /* ------------------------------------------------------------------------------------    */
  1925. OSErr SD_SetupImageData(
  1926.     gxRasterImageDataHdl hImageData)        // raster image data stuff
  1927. /*
  1928.     This message is called to setup the constant data used for imaging the entire job.
  1929. */
  1930. {
  1931.  
  1932.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  1933.     OSErr                        anErr;
  1934.     gxRasterImageDataPtr        pImageData;
  1935.     Boolean                     isJobNotFinalQuality, isTextJobFormatMode;
  1936.     long                        imagewriterOptions;
  1937.     
  1938.     // do the default setup
  1939.     anErr = Forward_GXSetupImageData(hImageData);
  1940.     nrequire(anErr, Forward_GXSetupImageData);
  1941.     
  1942.     // test for 'final' quality mode
  1943.     isJobNotFinalQuality = !JobIsBest(&imagewriterOptions);
  1944.     
  1945.     // test for textJobFormatMode
  1946.     isTextJobFormatMode = ( GXGetJobFormatMode( GXGetJob() ) == gxTextJobFormatMode);
  1947.             
  1948.     // if the job is not final quality or using textJobFormatMode, downgrade the imaging data to our lower quality
  1949.     if (isJobNotFinalQuality  ||  isTextJobFormatMode)
  1950.         {
  1951.         // ROUGH OR TEXT MODE
  1952.         
  1953.         // dereference for size and speed    
  1954.         pImageData = *hImageData;
  1955.                 
  1956.         // image at 80 or 72 dpi
  1957.         if (imagewriterOptions & kSuperRes)
  1958.             pImageData->hImageRes = ff(80);
  1959.         else
  1960.             pImageData->hImageRes = ff(72);
  1961.         pImageData->vImageRes = ff(72);
  1962.         
  1963.         // textJobFormatMode loads up the draft table, else setup halftones
  1964.         if (isTextJobFormatMode)
  1965.             {
  1966.             Handle            draftTable;
  1967.  
  1968.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID, &draftTable);
  1969.             nrequire(anErr, FailedToLoadDraftTable);
  1970.             
  1971.             // store away the draft table
  1972.             (**hGlobals).draftTable = draftTable;
  1973.  
  1974.             // Download something?    
  1975.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID+1, &draftTable);
  1976.             if (anErr == resNotFound)
  1977.                 {
  1978.                 draftTable = nil;
  1979.                 anErr = noErr;
  1980.                 }
  1981.             nrequire(anErr, GetDownloadTable);    
  1982.         
  1983.             if (draftTable)
  1984.                 {
  1985.                 HLock(draftTable);
  1986.                 anErr = Send_GXBufferData(*draftTable, GetHandleSize(draftTable), gxDontSplitBuffer);
  1987.                 DisposHandle(draftTable);
  1988.                 nrequire(anErr, SendDownloadTable);
  1989.                 }
  1990.             }
  1991.         else
  1992.             {            
  1993.             // use dither level that will look better at 72 dpi 
  1994.             // resolution than our default values (MAYBE: 4 is the default now anyway)
  1995.             pImageData->theSetup.planeSetup[0].planeHalftone.method = 4;
  1996.             
  1997.             // of course, turn off color matching when in non-final mode!
  1998.             pImageData->theSetup.planeSetup[0].planeProfile = nil;
  1999.             }
  2000.             
  2001.         if (isJobNotFinalQuality)
  2002.             {
  2003.             if (imagewriterOptions & kSuperRes)
  2004.                 {
  2005.                 // use bidirectional instead of unidirectional
  2006.                 // and also <esc>N instead of <esc>p for quality mode
  2007.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+3;
  2008.                 }
  2009.             else
  2010.                 {
  2011.                 // use bidirectional instead of unidirectional
  2012.                 // and also <esc>n instead of <esc>p for quality mode
  2013.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+2;
  2014.                 }
  2015.             }
  2016.         
  2017.         // packaging data
  2018.         pImageData->packagingInfo.headHeight         = 8;        // 8 pins (instead of 16)
  2019.         pImageData->packagingInfo.numberPasses         = 1;        // in 1 head pass (instead of 2)
  2020.         pImageData->packagingInfo.passOffset         = 0;        // with no space between passes
  2021.         }
  2022.     else
  2023.         {
  2024.         // FINAL QUALITY
  2025.         
  2026.         // dereference for size and speed    
  2027.         pImageData = *hImageData;
  2028.                 
  2029.         // image at 160 or 144 dpi
  2030.         if (imagewriterOptions & kSuperRes)
  2031.             {
  2032.             pImageData->hImageRes = ff(160);
  2033.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+1;
  2034.             }
  2035.         else
  2036.             {
  2037.             pImageData->hImageRes = ff(144);
  2038.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+0;
  2039.             }
  2040.         }
  2041.     
  2042.     // not a color ribbon?  Setup for black and white - do a B/W halftone rather than a dither
  2043.     if (!PrinterHasColorRibbon(GXGetJobOutputPrinter(GXGetJob())))
  2044.         {
  2045.         // dereference for size and speed    
  2046.         pImageData = *hImageData;
  2047.  
  2048.         // one plane, no color flags, move the halftone info up into correct position
  2049.         pImageData->theSetup.planes = 1;
  2050.         pImageData->theSetup.depth = 1;
  2051.         pImageData->packagingInfo.colorPasses = 1;
  2052.         pImageData->packagingInfo.packageOptions = 0;
  2053.         pImageData->theSetup.planeSetup[0].planeSpace = gxNoSpace;
  2054.         pImageData->theSetup.planeSetup[0].planeSet = nil;
  2055.         pImageData->theSetup.planeSetup[0].planeProfile = nil;
  2056.         pImageData->theSetup.planeSetup[0].planeOptions = gxDefaultOffscreen;
  2057.         pImageData->theSetup.planeSetup[0].planeHalftone.method = gxRoundDot;
  2058.         pImageData->theSetup.planeSetup[0].planeHalftone.tintSpace = gxRGBSpace;
  2059.         }
  2060.  
  2061.     return(noErr);
  2062.     
  2063. // EXCEPTION HANDLING
  2064. SendDownloadTable:
  2065. GetDownloadTable:
  2066.     DisposHandle((**hGlobals).draftTable);
  2067.     (**hGlobals).draftTable = nil;
  2068.     
  2069. FailedToLoadDraftTable:
  2070. Forward_GXSetupImageData:
  2071.     return(anErr);
  2072.     
  2073. } // SD_SetupImageData
  2074.  
  2075. /* ------------------------------------------------------------------------------------    */
  2076. OSErr SD_FetchDriverData(
  2077.     ResType            theType,
  2078.     short            theID,
  2079.     Handle*            theData)
  2080. {
  2081.  
  2082.     OSErr    anErr;
  2083.     
  2084.     anErr = Forward_GXFetchTaggedDriverData(theType, theID, theData);
  2085.     
  2086.     // do the translation at the proper DPI by modifying the old API
  2087.     // customization resource
  2088.     if ( (anErr   == noErr)    &&                 // got the resource okay
  2089.          (theType == 'cust')   &&                // it was a customization resource 
  2090.          (theID   == -8192)   )                    // with the old API id
  2091.         {
  2092.         long imagewriterOptions;
  2093.         
  2094.         if (!JobIsBest(&imagewriterOptions))
  2095.             {
  2096.             **((short**)theData)   = 72;
  2097.             **((short**)theData+1) = 72;
  2098.             }
  2099.         }
  2100.         
  2101.     return(anErr);
  2102.     
  2103. } // SD_FetchDriverData
  2104.  
  2105.  
  2106. /* ------------------------------------------------------------------------------------    */
  2107. OSErr SD_RenderPage(    gxFormat                theFormat,
  2108.                         gxShape                    thePage,
  2109.                         gxPageInfoRecord        *pageInfo,
  2110.                         gxRasterImageDataHdl    imageInfo)
  2111. /*
  2112.     The message sent to render an entire page.
  2113. */
  2114. {
  2115.  
  2116.     OSErr    theError = noErr;
  2117.  
  2118.     // if not text mode, do it the normal (raster) way
  2119.     if (GXGetJobFormatMode(GXGetJob()) != gxTextJobFormatMode) 
  2120.         {
  2121.         gxRectangle            paperSize;
  2122.         Str63                formLength;            // should be more than big enough for form skipping
  2123.         char                aNumber[8];
  2124.         char                len = 0;
  2125.         short                formLen;            // form length (in 144 dpi)
  2126.         short                i;
  2127.         
  2128.         
  2129.         // find out how big our paper is
  2130.         GXGetPaperTypeDimensions(GXGetFormatPaperType(theFormat), nil, &paperSize);
  2131.         
  2132.         // determine the left margin (in pixels)
  2133.         {
  2134.         SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  2135.         SpecGlobalsPtr            pGlobals;
  2136.         gxRasterImageDataPtr    pImageData;
  2137.  
  2138.         check(hGlobals);
  2139.  
  2140.         // dereference for size and speed    
  2141.         pImageData     = *imageInfo;
  2142.         pGlobals = *hGlobals;
  2143.         paperSize.left += ff(18);        // ImageWriter's can't go tighter than .25 inch
  2144.         if (paperSize.left > 0)
  2145.             paperSize.left = 0;
  2146.         pGlobals->leftMargin     = FixedToInt(
  2147.                                     FixMul(-paperSize.left, 
  2148.                                         FixDiv(pImageData->hImageRes, ff(72))));
  2149.         
  2150.         // set this to be the top of form
  2151.         formLength[len++] = ESCAPE;
  2152.         formLength[len++] = 'v';
  2153.  
  2154.         // set the form length to be the size of the page iff ImageWriterII
  2155.         if (pGlobals->isImageWriterII)
  2156.             {
  2157.             formLength[len++] = ESCAPE;
  2158.             formLength[len++] = 'H';
  2159.             formLen = FixedToInt(FixMul(paperSize.bottom-paperSize.top, ff(2)) );    // length is set in 144 dpi
  2160.             NumToString(formLen, aNumber);
  2161.             for (i = 0; i < 4-aNumber[0]; ++i)
  2162.                 formLength[len++] = '0';
  2163.             for (i = 1; i <= aNumber[0]; ++i)
  2164.                 formLength[len++] = aNumber[i];
  2165.             }
  2166.         }
  2167.  
  2168.         // NOW: move over the top margin
  2169.         formLen = -FixedToInt( FixMul(paperSize.top, ff(2)) );
  2170.         
  2171.             // Forward line feed
  2172.             formLength[len++] = ESCAPE;
  2173.             formLength[len++] = 'f';
  2174.  
  2175.             // send multiples of 99
  2176.             if (formLen >= 99)
  2177.                 {
  2178.                 formLength[len++] = ESCAPE;
  2179.                 formLength[len++] = 'T';
  2180.                 formLength[len++] = '9';
  2181.                 formLength[len++] = '9';
  2182.                 while (formLen >= 99)
  2183.                     {
  2184.                     formLength[len++] = 0x0A;        // line feed
  2185.                     
  2186.                     formLen -= 99;
  2187.                     }
  2188.                 }
  2189.                 
  2190.             // send remaining line feeds
  2191.             if (formLen > 0)
  2192.                 {
  2193.                 formLength[len++] = ESCAPE;
  2194.                 formLength[len++] = 'T';
  2195.                 NumToString(formLen, aNumber);
  2196.                 if (aNumber[0] == 1)
  2197.                     {
  2198.                     formLength[len++] = '0';
  2199.                     formLength[len++] = aNumber[1];
  2200.                     }
  2201.                 else
  2202.                     {
  2203.                     formLength[len++] = aNumber[1];
  2204.                     formLength[len++] = aNumber[2];
  2205.                     }
  2206.                 formLength[len++] = 0x0A;        // line feed
  2207.                 }
  2208.  
  2209.  
  2210.         // we've got all of this data, now send it
  2211.         theError = Send_GXBufferData(&formLength[0], len, gxNoBufferOptions );
  2212.         nrequire(theError, SetFormLength);        
  2213.                 
  2214.         // continue with normal rendering
  2215.         theError = Forward_GXRenderPage(theFormat, thePage, pageInfo, imageInfo);
  2216.         } 
  2217.     else 
  2218.         {
  2219.         theError = PrintPageInDraftMode(thePage, imageInfo);
  2220.         }
  2221.  
  2222. failed_WrongShape:
  2223. SetFormLength:
  2224.     return(theError);
  2225.     
  2226. } // SD_RenderPage
  2227.  
  2228.  
  2229. //<FF>
  2230. /* ------------------------------------------------------------------------------------    */
  2231. /*    SPECIFIC DRIVER RASTER OVERRIDES                                                    */
  2232. /* ------------------------------------------------------------------------------------    */
  2233. OSErr SD_LineFeed (
  2234.     short *lineFeedSize,                         // amount to line feed by
  2235.     Ptr buffer, unsigned long    * bufferPos,     // data goes here
  2236.     gxRasterImageDataHdl hImageData)            // raster image data stuff
  2237. /*
  2238.     Message is sent to output paper advance commands to the printer
  2239. */
  2240. {
  2241.  
  2242.     OSErr    anErr;
  2243.     Boolean    amLowRes;
  2244.     short    actualLineFeed = *lineFeedSize;
  2245.     
  2246.     amLowRes = ((**hImageData).vImageRes == ff(72));
  2247.     // if we are in low res mode, we double the line feed size, as all ImageWriter 
  2248.     // line feed commands are expressed at 144 dpi.
  2249.     if (amLowRes)
  2250.         *lineFeedSize <<= 1;
  2251.     
  2252.     // optimize small motions (particularlly -1 followed by +1 with no data between)
  2253.     // into groups.  This gets rid of the "paper dance" for blank colors passes.
  2254.     {    
  2255.     SpecGlobalsHdl    hGlobals = GetMessageHandlerInstanceContext();
  2256.     SpecGlobalsPtr    pGlobals = *hGlobals;
  2257.     
  2258.     if (    (pGlobals->packagingOptions == kDoSmallLineFeeds) || 
  2259.             (*lineFeedSize < -1) || 
  2260.             (*lineFeedSize > 1) )
  2261.         {
  2262.         *lineFeedSize += pGlobals->lineFeeds;
  2263.         pGlobals->lineFeeds = 0;
  2264.         // do the line feed in the default way
  2265.         anErr = Forward_GXRasterLineFeed(lineFeedSize, buffer, bufferPos, hImageData);
  2266.         }
  2267.     else
  2268.         {
  2269.         pGlobals->lineFeeds += *lineFeedSize;
  2270.         *lineFeedSize = 0;
  2271.         anErr = noErr;
  2272.         }
  2273.     }
  2274.     
  2275.     // and if in low quality mode, we divide the result to make up for the multiplication
  2276.     // that we do above
  2277.     if (amLowRes)
  2278.         *lineFeedSize >>= 1;    
  2279.             
  2280.     return(anErr);
  2281.     
  2282. } // SD_LineFeed
  2283.  
  2284. //<FF>
  2285. /* ------------------------------------------------------------------------------------    */
  2286. OSErr SD_PackageBitmap (
  2287.     gxRasterPackageBitmapRec    *pPackage,
  2288.     Ptr                         buffer,     // data goes here + bufferPos
  2289.     unsigned long                 *bufferPos,    // how much of the buffer already is full
  2290.     gxRasterImageDataHdl         hImageData)    // private image data
  2291. /*
  2292.     Packages a bitmap for the ImageWriter
  2293.     This routine is called in order to add your rotated and packaged pixel
  2294.     data to the buffer.  It is called once for each head pass.  This routine
  2295.     is pretty complex because it also does IW run length compression.  
  2296.     
  2297.     It must do the following:
  2298.         
  2299.     1)    Start filling the buffer from buffer+bufferPos.  Remember
  2300.         that this pointer may not be word aligned - so be careful
  2301.         assigning things into it.
  2302.         
  2303.     2)    If your printer does SetMargins, put a "fake" set of commands at
  2304.         the begining of the data.  Since most of the time you don't
  2305.         know the margins, you can save away the value of the bufferPos,
  2306.         and backpatch it after you have finished with the offscreen.
  2307.         SetMargins is used on printers that allow you to not send starting
  2308.         and ending whitespace.
  2309.         
  2310.     3)    Add in the rotated data for your printer.  The data to stuff starts
  2311.         at location startY in hOffscreen.  Stuff the bits from here until
  2312.         you reach startY+<your band size>, which is the size of your single
  2313.         band in this resolution mode.  Increment your number by 
  2314.         <your pass offset> + 1, which is the number of microspaces
  2315.         you will send between head passes to form this band.   Take care
  2316.         that you don't step off of the end of the offscreen in this operation,
  2317.         you may be called with startY at the end of the offscreen if the first part
  2318.         of the band is white.
  2319.         
  2320.         colorBand contains the color band which you should be stuffing, from
  2321.         1 to the number of color passes your printer needs (usually 4).
  2322.         Pack in the correct color band.  The packager will call you once
  2323.         for each color band, and correctly handle line feeds and backward
  2324.         line feeds to do the correct thing.  If your printer takes full
  2325.         RGB or CYMK data, I would define your number of colors to be
  2326.         1 and pack the full RGB or CYMK data with the one call to StuffBuffers.
  2327.         
  2328.         If you request kSendAllColors in your raster pack resource, then this
  2329.         message will always be called for all color passes, even those that
  2330.         do not have data on them.  For some printers, this is useful.  For the
  2331.         case of the ImageWriter, this option is not specified, so this message
  2332.         will only be sent for colors that actually have dirty bits within them.
  2333.         
  2334.     4)    Backpatch SetMargins from your saved value in step 2) now that you
  2335.         know the margins.
  2336.         
  2337.     5)    Increment bufferPos by the number of bytes you have
  2338.         added to the buffer.  Be sure to take into account the Set Margins
  2339.         command if you added one.
  2340.  
  2341.     
  2342. */
  2343. {
  2344. #pragma unused (isColorDirty)
  2345.  
  2346.     OSErr                    anErr;                    // would you beleive we could make mistakes?
  2347.     ScanLinePtr                pTheScanLine;            // Pointer to the start of scan line data
  2348.     unsigned short            lastDirtyCol;            // Last dirty part of the scan line
  2349.     unsigned short            firstDirty;                // First dirty pixel
  2350.     unsigned short            lastDirty;                // Last dirty pixel
  2351.     Boolean                    bandIsDirty;            // Is this band dirty?
  2352.     unsigned short            numberBytesAdded;        // Number of bytes we have added to the row
  2353.     unsigned short            repeatCount;            // Number of times we have seen this bitmap
  2354.     
  2355.     register unsigned short    whichCol;                // Index into the scan line data
  2356.     register unsigned short    x,y;                    // Index values into the offscreen
  2357.         
  2358.     register Ptr            thePtr;                    // Pointer to each Y scanline
  2359.     register unsigned char    tempColumn;                // Placeholder for the working column
  2360.     unsigned char            lastColumn;                // What was in the contents of the last column?
  2361.     
  2362.     Ptr                        basePtr;                // Pointer to current X byte
  2363.     unsigned char            outputMask;                // Mask of bit to set in rotated image
  2364.     unsigned char            inputMask;                // Mask of bit to look at in X
  2365.     unsigned char            startingInputMask;        // Mask of first bit of interest
  2366.     unsigned short            yPointerOffset;            // Increment pointer by this to get to next scanline
  2367.     
  2368.     unsigned short            endY, endX, incrY;        // To remove loop invariants.
  2369.     unsigned short            packingColor;            // number of colors packing
  2370.     unsigned long             originalBufferPos;        // where we were in the buffer before we started;
  2371.     short                    originalLineFeeds;        // how many line feeds did we have before?
  2372.     SpecGlobalsHdl            hGlobals = GetMessageHandlerInstanceContext();
  2373.     SpecGlobalsPtr            pGlobals = *hGlobals;
  2374.     
  2375. /* This macro stores one group into the pointer:
  2376.     P = Pointer to fill into
  2377.     G = Character for group
  2378.     S = Length of group run in pixels
  2379. */
  2380. #define EMITGROUP(P, G, S)                    \
  2381.         P->cEscape = ESCAPE;                \
  2382.         P->cCommand = G;                    \
  2383.         Long2Dec(S, P->cLineLength);        
  2384.  
  2385.     // save away original position in order to do a restore should the band be clean
  2386.     originalBufferPos = *bufferPos;
  2387.     originalLineFeeds = pGlobals->lineFeeds;
  2388.     if (originalLineFeeds == 0)
  2389.         {
  2390.         anErr = noErr;
  2391.         }
  2392.     else
  2393.         {
  2394.         // if we have any extra line feeds saved up, do them now!    
  2395.         pGlobals->lineFeeds = 0;
  2396.         pGlobals->packagingOptions = kDoSmallLineFeeds;
  2397.         anErr = Send_GXRasterLineFeed(&originalLineFeeds, buffer, bufferPos, hImageData);
  2398.         pGlobals = *hGlobals;
  2399.         pGlobals->packagingOptions = kNoPackagingOptions;
  2400.         }
  2401.     nrequire(anErr, SendInitialLineFeeds);
  2402.     
  2403.     /* Set color iff ImageWriterII */
  2404.     if ((**hGlobals).isImageWriterII)
  2405.         {
  2406.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos));
  2407.         
  2408.         /* Set color mode for this scan line, if needed */
  2409.         pTheScanLine->cColorEscape        = ESCAPE;
  2410.         pTheScanLine->cSetColorCommand    = kSetColorCommand;
  2411.         
  2412.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2413.         if (packingColor == 4)
  2414.             switch (pPackage->colorBand)
  2415.                 {
  2416.                 case 1: // yellow
  2417.                     pTheScanLine->cColor    = '1';
  2418.                     startingInputMask = 0x10;
  2419.                     break;
  2420.                     
  2421.                 case 2: // magenta
  2422.                     pTheScanLine->cColor    = '2';
  2423.                     startingInputMask = 0x20;
  2424.                     break;
  2425.     
  2426.                 case 3: // cyan
  2427.                     pTheScanLine->cColor    = '3';
  2428.                     startingInputMask = 0x40;
  2429.                     break;
  2430.                     
  2431.                 case 4: // black
  2432.                     pTheScanLine->cColor    = '0';
  2433.                     startingInputMask = 0x80;
  2434.                     break;
  2435.                     
  2436.                 }
  2437.         else
  2438.             {
  2439.             pTheScanLine->cColor = '0';
  2440.             startingInputMask = 0x80;
  2441.             }
  2442.         }
  2443.     else    /* Backup to eliminate cColorEscape, cSetColorCommand and cColor */
  2444.         {
  2445.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos) - 3);
  2446.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2447.         startingInputMask = 0x80;
  2448.         }
  2449.  
  2450.     /* Start with the first bit in the offscreen */
  2451.     inputMask = startingInputMask;
  2452.         
  2453.     /* We start out with no dirty bits */
  2454.     firstDirty = 0;
  2455.     lastDirty = 0;
  2456.     bandIsDirty = false;
  2457.     
  2458.     /* Set our array index to zero */
  2459.     whichCol = 0;
  2460.     lastDirtyCol = 0;
  2461.     numberBytesAdded = 0;
  2462.     
  2463.     /* Set up RLL variables */
  2464.     repeatCount = 0;
  2465.     lastColumn = 0;
  2466.     
  2467.     /* Get the byte pointer for the start of this color band */
  2468.     basePtr = pPackage->bitmapToPackage->image;
  2469.     
  2470.     /* Get the byte pointer for the start of the first scan line */ 
  2471.     basePtr += pPackage->startRaster * pPackage->bitmapToPackage->rowBytes;
  2472.             
  2473.     /* Save away loop invariants */
  2474.     endY     = pPackage->startRaster + (*hImageData)->packagingInfo.headHeight;        // Ending scan line
  2475.     incrY     = (*hImageData)->packagingInfo.passOffset + 1;            // Number of scanlines to increment by
  2476.     endX     = pPackage->dirtyRect.right;                                // Ending X pos
  2477.     yPointerOffset = incrY * pPackage->bitmapToPackage->rowBytes;            // amount to add to the input
  2478.                                                             // pointer to move to the next scanline
  2479.  
  2480.     /* If the ending position is too large for the bitmap we have been given,
  2481.        truncate it, so that we don't print garbage */
  2482.     if (endY > pPackage->bitmapToPackage->height)
  2483.         endY = pPackage->bitmapToPackage->height;
  2484.     
  2485.     /* For the entire width of the offscreen, move a rolling mask along in the
  2486.        X direction, rotating up 8 bits of Y data per column.  In addition, compress
  2487.        runs of columns that are > 14 length. */
  2488.     for (x = 0; x < endX; x++)
  2489.         {        
  2490.         /* The bits in this column are clear to begin with */
  2491.         tempColumn = 0;
  2492.         
  2493.         /* Which byte to look at in the input buffer */
  2494.         thePtr = basePtr;
  2495.         
  2496.         /*     Where to place the bit in the output. The ImageWriter takes the bit
  2497.             pattern upside down. */
  2498.         outputMask = 0x01;
  2499.         
  2500.         /* Scan through this band, setting each of the 8 bits == the bit in that scan line */
  2501.         for (y = pPackage->startRaster; y < endY; y += incrY)
  2502.             {
  2503.             /* If we have a bit in the input, rotate it into the output */
  2504.             if ((*thePtr) & inputMask)
  2505.                 tempColumn |= outputMask;
  2506.  
  2507.             // move onto next position in the output data                
  2508.             outputMask <<= 1;
  2509.             
  2510.             // move onto the next scan line in the input data
  2511.             thePtr += yPointerOffset;
  2512.             } // for y
  2513.             
  2514.             
  2515.         /* Save the column info */ 
  2516.         pTheScanLine->iTheData[whichCol] = tempColumn;
  2517.         
  2518.         /* Get the next bit from the current pointer */
  2519.         inputMask >>= packingColor;
  2520.         if (!inputMask)
  2521.             {
  2522.             /* If we run out of bits, get the next byte */
  2523.             basePtr++;
  2524.             
  2525.             /* And reset the bit mask to the first bit */
  2526.             inputMask = startingInputMask;
  2527.             }
  2528.             
  2529.         /* If we have some form of data */
  2530.         if (tempColumn != 0)
  2531.             {
  2532.             if (!bandIsDirty)
  2533.                 {
  2534.                 /* This is the first dirty pixels we have so far */
  2535.                 bandIsDirty = true;
  2536.                 firstDirty = x;
  2537.                 }
  2538.             
  2539.             /* This is also the last dirty pixels so far */
  2540.             lastDirty = x;
  2541.             } // SetDirty
  2542.             
  2543.         /* If we have some dirty bits */
  2544.         if (bandIsDirty)
  2545.             {
  2546.             /* Move on to the next column */
  2547.             whichCol++;
  2548.             
  2549.             /* If this is a dirty column, then it is the last one so far */
  2550.             if (tempColumn != 0)
  2551.                 lastDirtyCol = whichCol;
  2552.             
  2553.             /* If we have a duplication, up the repeat count */
  2554.             if (tempColumn == lastColumn) // if (false) // turn off repeat groups
  2555.                 {
  2556.                 repeatCount++;
  2557.                 if (repeatCount == 14)
  2558.                     {
  2559.                     /* Kick out the old group */
  2560.                     whichCol -= 14;
  2561.                         EMITGROUP(pTheScanLine, kGraphicsCommand, whichCol);
  2562.                         numberBytesAdded += whichCol + kGroupSize;
  2563.                         pTheScanLine = (ScanLinePtr)(((Ptr) pTheScanLine) +
  2564.                             whichCol + kGroupSize);
  2565.                     
  2566.                     whichCol = 1;
  2567.                     lastDirtyCol = 1;
  2568.                     pTheScanLine->iTheData[0] = tempColumn;
  2569.                     }
  2570.                 }
  2571.             else
  2572.                 {
  2573.                 /* If we were repeating, emit the repeat group */
  2574.                 if (repeatCount >= 14)
  2575.                     {
  2576.                     EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2577.                     numberBytesAdded += 1 + kGroupSize;
  2578.                     pTheScanLine = (ScanLinePtr) (((Ptr) pTheScanLine) + 
  2579.                         1 + kGroupSize);
  2580.                         
  2581.                     whichCol = 1;
  2582.                     lastDirtyCol = 1;
  2583.                     pTheScanLine->iTheData[0] = tempColumn;
  2584.                     }
  2585.                 repeatCount = 0;
  2586.                 lastColumn = tempColumn;
  2587.                 }
  2588.                 
  2589.             } // BandIsDirty
  2590.             
  2591.         } // end of loop for width of bitmap
  2592.  
  2593.     /* if we have a dirty band - emit the final bit of data we have
  2594.        packaged up */
  2595.     if (bandIsDirty)
  2596.         {            
  2597.         
  2598.         /* Set the margins to be the first and last dirty pixels in the scan line -
  2599.            the ImageWriter only does left margin optimization. */
  2600.         {
  2601.             SetMarginsPtr        marginBuffer;
  2602.             SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  2603.             
  2604.             check(hGlobals);
  2605.             
  2606.             /* Get the location for placing the set margin command */
  2607.             marginBuffer = (SetMarginsPtr) (buffer + (*bufferPos));
  2608.             
  2609.             /* Stuff in the set margin command */
  2610.             marginBuffer->cEscape  = ESCAPE;
  2611.             marginBuffer->cCommand = kSetMarginsCommand;
  2612.             
  2613.             /* convert left margin into ASCII and place it at the start of the buffer */
  2614.             Long2Dec((**hGlobals).leftMargin + firstDirty, (Ptr)(marginBuffer->cIndentDistance));
  2615.         }
  2616.         
  2617.         /* Send the last group command */
  2618.         if (repeatCount < 14)
  2619.             {
  2620.             /* Emit a normal group */
  2621.             EMITGROUP(pTheScanLine, kGraphicsCommand, lastDirtyCol);
  2622.             numberBytesAdded += lastDirtyCol + kGroupSize;
  2623.             }
  2624.         else
  2625.             {
  2626.             /* Don't stuff a final repeat group if it's blank space */
  2627.             if (tempColumn != 0)
  2628.                 {
  2629.                 /* Emit a repeat group */
  2630.                 EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2631.                 numberBytesAdded += 1 + kGroupSize;
  2632.                 }
  2633.             } // end of repeatCount < 14
  2634.                     
  2635.         
  2636.         /*    Increment the count of the buffer by bytes added for groups, plus
  2637.             the header, if any, plus the set margins command */
  2638.         (*bufferPos) += numberBytesAdded + kScanLineSize + kSetMarginsSize;
  2639.  
  2640.         /* and put a <cr> at the end of the line */
  2641.         *(char*)(buffer + (*bufferPos)) = '\n';
  2642.         (*bufferPos) += 1;
  2643.         
  2644.         } // bandIsDirty
  2645.     else
  2646.         {
  2647.         // don't output data if we didn't have any!
  2648.         *bufferPos = originalBufferPos;
  2649.  
  2650.         // restore original number of line feeds
  2651.         pGlobals = *hGlobals;
  2652.         pGlobals->lineFeeds = originalLineFeeds;
  2653.         } // band is not dirty
  2654.         
  2655.     // always return your errors!
  2656. SendInitialLineFeeds:
  2657.     return(anErr);
  2658.     
  2659. } // SD_PackageBitmap
  2660.  
  2661.  
  2662. /*    ______________________________________________________________
  2663.  
  2664.     SD_DefaultDesktopPrinter -
  2665.     
  2666.     This routine is a total override of the gxDefaultDesktopPrinter
  2667.     message.
  2668.     
  2669.     WHY THIS IS IMPORTANT:
  2670.     
  2671.     It stores the name of the desktop printer GX just created
  2672.     in our global "class context" data.  This way, we can retrieve
  2673.     the name from our gxChooserMessage override, use the name to
  2674.     identify the desktop printer file, and rename it.
  2675.  
  2676.     ______________________________________________________________    */
  2677.  
  2678. OSErr SD_DefaultDesktopPrinter(Str31 dtpName)
  2679. {
  2680.     OSErr                    err;
  2681.     ChooserGlobalsHdl        hGlobals;
  2682.  
  2683.     err = Forward_GXDefaultDesktopPrinter(dtpName);
  2684.     nrequire(err, ErrorOccurred);
  2685.  
  2686. /*
  2687.     Set up our class context globals, if there's no handle already stored
  2688.     there.  Then, copy the dtp name into these globals.  This handle gets
  2689.     tossed in our gxChooserMessage override.  Why use the class
  2690.     context instead of the instance context?  Because a different
  2691.     instance of our code receives the gxDefaultDesktopPrinter message
  2692.     than the gxChooserMessage.  Setting the instance context won't get
  2693.     the data to our gxChooserMessage override.
  2694. */
  2695.     hGlobals = (ChooserGlobalsHdl) GetMessageHandlerClassContext();
  2696.     if (hGlobals == nil)
  2697.     {
  2698.         hGlobals = (ChooserGlobalsHdl) TempNewHandle(sizeof(ChooserGlobals), &err);
  2699.         nrequire(err, ErrorOccurred);
  2700.         (*hGlobals)->ownerCount = 0;
  2701.         SetMessageHandlerClassContext(hGlobals);
  2702.     }
  2703.  
  2704.     ++(*hGlobals)->ownerCount;
  2705.     BlockMove(dtpName, &(*hGlobals)->dtpName, (long) dtpName[0] +1L);
  2706.  
  2707. ErrorOccurred:
  2708.     return err;
  2709. }
  2710.  
  2711.  
  2712. /*    ______________________________________________________________
  2713.  
  2714.     SD_ChooserMessage -
  2715.     
  2716.     This routine is a total override of the gxChooserMessage
  2717.     message.
  2718.     
  2719.     WHY THIS IS IMPORTANT:
  2720.     
  2721.     This routine checks for "left button" presses, which indicate
  2722.     that the Chooser's "Create" button was pressed.  In this case,
  2723.     after forwarding the message so that the DTP is created, we
  2724.     rename the DTP.
  2725.  
  2726.     ______________________________________________________________    */
  2727.  
  2728. OSErr SD_ChooserMessage(short message, short caller, StringPtr objName,
  2729.                         StringPtr zoneName, ListHandle theList, long p2)
  2730. {
  2731.     OSErr                err;
  2732.     ChooserGlobalsHdl    hGlobals;
  2733.  
  2734. /*
  2735.     Forward the message so that GX handles the Chooser message
  2736.     appropriately.  If the user hit Create, rename the DTP as
  2737.     we like and clear our global data.
  2738. */
  2739.     err = Forward_GXChooserMessage(message, caller, objName, zoneName, theList, p2);
  2740.  
  2741.     if ((message == buttonMsg) && ((p2 & 0xFF) == 1))    // left button was hit.
  2742.     {
  2743.         if (!err) err = MyRenameDTPs();
  2744.  
  2745.         hGlobals = (ChooserGlobalsHdl) GetMessageHandlerClassContext();
  2746.  
  2747.         if (hGlobals && (--(*hGlobals)->ownerCount == 0))
  2748.         {
  2749.             DisposHandle((Handle) hGlobals);
  2750.             SetMessageHandlerClassContext(nil);
  2751.         }
  2752.     }
  2753.  
  2754.     return err;
  2755. }
  2756.  
  2757.  
  2758. /*    ______________________________________________________________
  2759.  
  2760.     MyRenameDTPs -
  2761.     
  2762.     This routine renames the desktop printer whose name is
  2763.     stored in our class context data by SD_DefaultDesktopPrinter.
  2764.     In this example, we try to rename the DTP "Dave's DTP" and
  2765.     then append a "1, 2, 3…" as necessary if that name is taken.
  2766.     You'd probably want to rename the DTP's to something a little
  2767.     more useful.
  2768.     
  2769.     WHY THIS IS IMPORTANT:
  2770.     
  2771.     This routine renames a newly created desktop printer file.
  2772.     Note that this routine assumes that desktop printer files
  2773.     are created on the desktop and that the default desktop
  2774.     printer name is stored in the System File in 'STR ' -8192.
  2775.     These assumptions are valid now, but subject to change under
  2776.     future versions of QuickDraw GX.
  2777.  
  2778.     ______________________________________________________________    */
  2779.  
  2780. OSErr MyRenameDTPs()
  2781. {
  2782.     OSErr                err = noErr;
  2783.     FSSpec                DTPFSSpec;
  2784.     short                vRefNum, loop = 0;
  2785.     Str63                numStr, newName = "\pDave's DTP";
  2786.     long                numLen, orgLen = newName[0] +1, parDirID;
  2787.     ChooserGlobalsHdl    hGlobals = (ChooserGlobalsHdl) GetMessageHandlerClassContext();
  2788.  
  2789. /*
  2790.     If our globals have been created, get the desktop folder's
  2791.     location and make an FSSpec for the desktop printer.
  2792. */
  2793.     require(hGlobals, NoGlobals);
  2794.     err = FindFolder(kOnSystemDisk, kDesktopFolderType, kCreateFolder,
  2795.                      &vRefNum, &parDirID);
  2796.  
  2797.     nrequire(err, FindFolder_Failed);
  2798.     err = FSMakeFSSpec(vRefNum, parDirID, (*hGlobals)->dtpName, &DTPFSSpec);
  2799.     nrequire(err, FSMakeFSSpec_Failed);
  2800.  
  2801.  
  2802. // Rename the DTP, appending a 1, 2, 3… as necessary.
  2803.  
  2804.     do
  2805.     {
  2806.         if (loop != 0)
  2807.         {
  2808.             NumToString(loop, numStr);
  2809.             numLen = numStr[0]+1;
  2810.             numStr[0] = ' ';
  2811.             BlockMove(numStr, &newName[orgLen], numLen);
  2812.             newName[0] = orgLen +numLen -1;
  2813.         }
  2814.  
  2815.         err = FSpRename(&DTPFSSpec, newName);
  2816.         loop++;
  2817.     }
  2818.     while (err == dupFNErr);
  2819.  
  2820.  
  2821. /*
  2822.     Remember to change the default printer string in the system
  2823.     file so that the newly named DTP will still be the default!
  2824.     Note that if the default string doesn't exist, we don't add
  2825.     one.  If a future version of GX no longer uses the 'STR '
  2826.     resource, there's no point in adding one.
  2827. */
  2828.     if (!err)
  2829.     {
  2830.         Handle    defaultString;
  2831.         short    oldResFile = CurResFile();
  2832.         
  2833.         UseResFile(0);
  2834.         defaultString = Get1Resource('STR ', -8192);
  2835.  
  2836.         if (defaultString)
  2837.         {
  2838.             RmveResource(defaultString);
  2839.             DisposHandle(defaultString);
  2840.             
  2841.             defaultString = NewHandle((long) newName[0] +1L);
  2842.             BlockMove(newName, *defaultString, (long) newName[0] +1L);
  2843.             AddResource(defaultString, 'STR ', -8192, "\p");
  2844.             WriteResource(defaultString);
  2845.             ReleaseResource(defaultString);
  2846.         }    
  2847.         
  2848.         UseResFile(oldResFile);
  2849.     }
  2850.     
  2851. FSMakeFSSpec_Failed:
  2852. FindFolder_Failed:
  2853. NoGlobals:
  2854.     return err;
  2855. }
  2856.